Every time I wanna divide 9 with 2 it prints out 4.0. Why not 4.5?? And how can i fix this??
Welcome to the Java Programming Forums
The professional, friendly Java community. 21,500 members and growing!
The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.
>> REGISTER NOW TO START POSTING
Members have full access to the forums. Advertisements are removed for registered users.
Every time I wanna divide 9 with 2 it prints out 4.0. Why not 4.5?? And how can i fix this??
Last edited by bornacvitanic; August 31st, 2012 at 06:24 AM.
You're doing int division which always returns an int (truncated to the nearest int). If you want a double result, you have to use at least one double in your statement:
double result = 9.0 / 2; // the 9.0 makes this double math // or this will work the same: result = 9 / 2.0; // or this result = (double) 9 / 2;
bornacvitanic (August 31st, 2012)
Tnx i tried it with doubles but it didnt work, but now i set all variables to double and it works!
I'm with you so far.
Actually it does not "truncate to the nearest int." It truncates by discarding any fractional part. Result is not necessarily the nearest int.
public class Z { public static void main(String [] args) { int x1 = 1000000/500001; int x2 = 1000000/499999; int y1 = -1000000/500001; int y2 = -1000000/499999; double f1 = (double)1000000/500001; double f2 = (double)1000000/499999; double g1 = -(double)1000000/500001; double g2 = -(double)1000000/499999; System.out.println("f1 = " + f1 + ", x1 = " + x1); System.out.println("f2 = " + f2 + ", x2 = " + x2); System.out.println("g1 = " + g1 + ", y1 = " + y1); System.out.println("g2 = " + g2 + ", y2 = " + y2); } }
Output:
f1 = 1.999996000008, x1 = 1 f2 = 2.000004000008, x2 = 2 g1 = -1.999996000008, y1 = -1 g2 = -2.000004000008, y2 = -2
Cheers!
Z
Last edited by Zaphod_b; August 31st, 2012 at 08:25 AM.
bornacvitanic (August 31st, 2012), curmudgeon (August 31st, 2012)
Thanks for the correction Z.