+ 1
division with whole numbers
public class FirstProgram { public static void main(String[] args) { double number = (1 / 3) * 3; System.out.println("(1/3) * 3 is equal to " + number); } } output: (1/3) * 3 is equal to 0.0 the final result should be 1.0, why its returns 0.0?
3 Antworten
+ 6
(1/3) is a integer division.
Use (1/3.0) to make double division. Or explicit casting (1/(double)3).
+ 5
It won't work with a fraction like 1/3. It equates this to 0. If you had two other variables for your numerator and denominator then it would work. Like this:
public class FirstProgram
{
public static void main(String[] args)
{
double one, two, ifn;
one = 1;
three = 3;
ifn = one/three;
System.out.print(ifn);
}
}
+ 3
This is because you're doing integer division first then multiplying and then implicitly converting that result to a double.
1/3 = 0 (With integer division the decimal part is truncated)
0 * 3 = 0
0 converted to double is 0.0