- 2
Too big a number made it negative...
So I made a code to multiply odd numbers by 3 and add 1, and divide even numbers by 2 and so on... Here is the code: import java.util.Scanner; public class Program { private static Scanner number; public static void main(String[] args) { System.out.println("input starting value"); number = new Scanner(System.in); int x= number.nextInt(); while(x > 1) if(x % 2 == 0){ x /= 2; System.out.println(x); } else{ x *= 3; x += 1; System.out.println(x); } } } When I input 999999999 I got -1294967298 as my answer. I am just wondering how that came to be what happened...
5 Respostas
+ 2
Youre using int, which doesn't go that high in value. If you exceed its max, you get what you got. Try using long instead of int.
+ 2
nope .u cant use integer.ur value has been reached upto -128 to 127 (256) which is the last range for an any integer value.so u will have to use double,long as a keyword.becoz they has a very long range.
+ 1
yes. Just keep in mind it uses up more memory so not advised if not needed.
0
Oh alright, I was just being stupid with the code anyway, thanks for the help!
0
np, best of luck on future codings :)