java中的模与类型转换
我正在查看Java中的以下代码:java中的模与类型转换,java,Java,我正在查看Java中的以下代码: public class MyClass { public static void main(String args[]) { int mod = (int) (1e9) + 7; int curValue = 483575207; int numFullRow = 237971068; long profit1 = 995913967; long profit2 = profit1;
public class MyClass {
public static void main(String args[]) {
int mod = (int) (1e9) + 7;
int curValue = 483575207;
int numFullRow = 237971068;
long profit1 = 995913967;
long profit2 = profit1;
int numSameColor = 3;
profit1 %= mod;
profit2 %= mod;
profit1 += (long)(curValue + curValue - numFullRow + 1) * numFullRow / 2 * numSameColor;
System.out.println(profit1 % mod);
profit2 += ((long)(curValue + curValue - numFullRow + 1) *numFullRow / 2 * numSameColor) % mod;
System.out.println(profit2);
}
}
profit1
和profit2
的输出结果不同,我不太理解profit2
无法按预期工作。操作员正在扰乱操作顺序。在这种情况下,profit2在添加到现有profit2之前进行mod,而profit one在执行mod运算符之前进行累积
您可以在此处阅读有关java运算符优先级的更多信息:
如果展开+=
步骤并创建本例中的profit3,则可以理解操作顺序:
int mod = (int) (1e9) + 7;
int curValue = 483575207;
int numFullRow = 237971068;
long profit1 = 995913967;
long profit2 = profit1;
long profit3 = profit1;
int numSameColor = 3;
profit1 %= mod;
profit2 %= mod;
long temp = (long)(curValue + curValue - numFullRow + 1) * numFullRow / 2 * numSameColor;
profit3 = profit3 + (temp % mod);
profit1 += temp;
System.out.println(profit1 % mod);
profit2 += ((long)(curValue + curValue - numFullRow + 1) *numFullRow / 2 * numSameColor) % mod;
System.out.println(profit2);
System.out.println(profit3);
哪一个不符合预期?