这是我的代码:
public static void main(String[] args) {
int f=1;//first number
int s=2;//second number
int fin=0;//final answer
int x;
System.out.println("1\n2");
for (x=3; x<4000000; x=f+s){
System.out.println(x);
f=s;
s=x;
if (x%2==0){
fin+=x;
}
}
System.out.println("Sum of all even number: "+fin+2);
}
出于某种原因,当实际答案是 4613732
时,我得到的是 46137302
作为我的最终答案。我不确定为什么我的答案是实际答案的十倍。
最佳答案
您偶然发现了 java 的漂亮字符串连接。以下作品:
System.out.println("Sum of all even number: " + (fin+2));
您必须明确地对数字求和。否则 Java 继续从左到右对值求和:您的字符串 + 实际数字,给出类似于 "Sum of all even number: 4613730"
的内容。然后附加 2
给出 “所有偶数的总和:46137302”
。但是您想先对数字求和:您需要将它们包装在 ()
中。
关于java - 欧拉项目编号 2 : Even Fibonacci numbers 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34533985/