-5
double h = 1/4;
System.out.println((1/4));
System.out.println(h);

Output:

0
0.0

I really don't know what to say. This exact way of dividing has always worked for me in the past. Why doesn't it work in this case? Also, (double)(1/4) and Math.floorDiv(1,4) both don't work as well I have tried that.

azro
  • 47,041
  • 7
  • 30
  • 65
yes
  • 1
  • 1
  • 2
    Are you maybe remembering doing 1.0 / 4.0? This will achieve what you want. – Cortex0101 Jan 09 '22 at 10:56
  • 1
    That didn't work in the past either, maybe you misremembered how to do it? Right now it's [integer division](https://stackoverflow.com/q/4685450/555045) and optionally converting to a double *afterwards* – harold Jan 09 '22 at 10:57
  • re: floorDiv "doesn't work". It is doing exactly what its [documentation](https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#floorDiv-int-int-) says it does: *Returns the largest (closest to positive infinity) int value that is less than or equal to the algebraic quotient.* For arguments 1 and 4, the algebraic quotient is 0.25, and the largest integer less than or equal to 0.25 is 0. – passer-by Jan 09 '22 at 14:33

1 Answers1

0

If all operand of a division are int, then you'll do int division and it would provide only an int value (or an int rounded value if you store in double)

At least one of the operand should be double

double h = 1.0 / 4;
System.out.println(h); // 0.25

h = 1d / 4;
System.out.println(h); // 0.25

h = 1 / 4.0;
System.out.println(h); // 0.25

h = ((double) 1) / 4;
System.out.println(h); // 0.25
azro
  • 47,041
  • 7
  • 30
  • 65