Des*_*Des -1 java int long-integer
This is a simple example of the problem:
public class IntVsLong {
public static void main(String[] args) {
int a = 3;
int b = 3;
long n = 549382313570L;
String s = "epsxyyflvrrrxzvnoenvpegvuonodjoxfwdmcvwctmekpsnamchznsoxaklzjgrqruyzavshfbmuhdwwmpbkwcuomqhiyvuztwvq";
System.out.println(a * n/s.length() + b); //returns 16481469410
System.out.println(a * (n/s.length()) + b); //returns 16481469408
}
}
Run Code Online (Sandbox Code Playgroud)
The first situation, without parentheses, returns 16481469410. The second one, with parentheses, returns 16481469408. Why?
This is because order of evaluation is different, and integer math rounds down. For an example with smaller numbers to show the point.
3 * (5 / 2) = 3 * (2) = 6
Run Code Online (Sandbox Code Playgroud)
without parentheses
3 * 5 / 2 = 15 / 2 = 7
Run Code Online (Sandbox Code Playgroud)
operations are evaluated left to right without parentheses, and when you reach the division statement, you lose some information because integers cannot hold fractional numbers. The earlier you lose this information in general the less accurate your final result.
| 归档时间: |
|
| 查看次数: |
42 次 |
| 最近记录: |