我正在为项目euler做数学挑战,我在运行程序时遇到了一个奇怪的问题.结果应该是所有奇数到10,000,000的总和,但我得到一个负数,我做错了什么?
package program;
import java.util.*;
public class MainClass {
/**
* @param args
*/
public static void main(String[] args) {
int total = 0;
for (int counter = 1; counter < 10000000; counter++) {
if (!((counter % 2) == 0)) {
total+=counter;
}
}
System.out.println(total);
}
Run Code Online (Sandbox Code Playgroud)
}
在int因为总太大变量不能保持总.在循环的某个时刻,你得到一个整数溢出,并且它"滚动"到一个负数:
你需要一个long.
在风格和效率方面,我会将代码更改为迭代,2以便您不需要对奇数进行测试:
public static void main(String[] args) {
long total = 0;
for (int counter = 1; counter < 10000000; counter += 2) { // iterate by 2
total += counter;
}
System.out.println(total);
}
Run Code Online (Sandbox Code Playgroud)