Every time I wanna divide 9 with 2 it prints out 4.0. Why not 4.5?? And how can i fix this??
Printable View
Every time I wanna divide 9 with 2 it prints out 4.0. Why not 4.5?? And how can i fix this??
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:
Code :
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;
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.
Code java:
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:
Code :
f1 = 1.999996000008, x1 = 1 f2 = 2.000004000008, x2 = 2 g1 = -1.999996000008, y1 = -1 g2 = -2.000004000008, y2 = -2
Cheers!
Z
Thanks for the correction Z.