问题
In the code below, when x = 60 and y = 2, result = 500. This is correct, but any x value between 60 and 119 also gives 500. Also, when x < 60, I get a divide by 0 error. Additionally, when x >= 120, result = 0. I am stumped as to why this is happening. I have also tried using various combinations of int, float, and long and still, no luck.
public class main {
static long result;
static int x;
static int y;
public static void main(String[] args) {
x = 60;
y = 2;
result = 1000 * (1 / (x / 60)) / y;
System.out.println(result);
}
}
By the way, I encountered this problem while trying to make a metronome application for Android. I took this code out of context to make it easier to isolate the problem. Any help and/or suggestions are very appreciated!
回答1:
The answer is not wrong, it's just not what you're expecting. You're using int division which will return an int result, a result that is truncated to the int result.
You want to do double division to get a double result, not int division which returns an int result.
// the 1.0 will allow for floating point division
result = (long) (1000 * (1.0 / (x / 60)) / y);
回答2:
Integer arithmetics say that
1999 / 100
is in fact 19, not 19.99 or 20, as you might expect.
If you do a division with integers, you will always get the floored result of the actual (mathematical) result.
回答3:
The equation could be simplified as
result = 1000 * 60 / (x * y);
If you want float division result:
result = long(1000 * 60.0 / (x * y));
If you want rounded float division result:
result = long(1000 * 60.0 / (x * y) + 0.5);
来源:https://stackoverflow.com/questions/18709340/performing-a-calculation-in-java-gives-completely-wrong-answer