- 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...

30th Aug 2016, 1:00 AM
Adam Lang
Adam Lang - avatar
5 odpowiedzi
+ 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.
30th Aug 2016, 2:54 AM
James
James - avatar
+ 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.
18th Sep 2016, 6:42 PM
Pranit Bhoir
Pranit Bhoir - avatar
+ 1
yes. Just keep in mind it uses up more memory so not advised if not needed.
30th Aug 2016, 2:59 AM
James
James - avatar
0
Oh alright, I was just being stupid with the code anyway, thanks for the help!
30th Aug 2016, 3:00 AM
Adam Lang
Adam Lang - avatar
0
np, best of luck on future codings :)
30th Aug 2016, 3:02 AM
James
James - avatar