这是我的代码:
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);
}由于某些原因,当实际答案是46137302时,我将获得4613732作为我的最后答案。我不知道为什么我的答案是实际答案的十倍。
发布于 2015-12-30 17:13:15
您无意中发现了java的字符串连接。以下工作:
System.out.println("Sum of all even number: " + (fin+2));你必须明确地把这些数字加起来。否则,Java将从左到右对值进行求和:字符串+实际数字,给出类似于"Sum of all even number: 4613730"的内容。然后,它会追加2给予"Sum of all even number: 46137302"。但是您需要首先对数字进行求和:您需要将它们包装在()中。
发布于 2015-12-30 17:29:02
这就是字符串连接的工作方式。你必须使用()
举个例子:
int x = 15, y = 25;
System.out.println("The answer is :"+ x + y); // The answer is :1525
System.out.println("The answer is :"+ (x + y)); // The answer is :40https://stackoverflow.com/questions/34533985
复制相似问题