When I try the code:
int a = read.nextInt();
int b = read.nextInt();
double x = a/b;
System.out.println(x);
with the input 10 and 6.
I get the output 1.0, but “x” being double should get the decimal answer. Only when I change variables “a” and “b” to double, I get the expected answer.
I don’t understand, since 10 and 6 are integers, why should that affect the final answer? (1,66666667)
To get the expected decimal answer, you should ensure that at least one of the operands in the division is a floating-point type (such as double
). By changing either a
or b
to a double, you force the division to be performed as a floating-point division, and the result will be a double with the decimal part included.
Try like this
int a = read.nextInt();
int b = read.nextInt();
double x = (double) a / b; // Perform floating-point division by casting ‘a’ to double
System.out.println(x);
2 Likes
Thanks a lot for your help