英文:
How to get the sum of Fibonacci sequence 0 to less than 500
问题
以下是您要翻译的内容:
问题是这样的:编写一个程序,找到从0到小于500的斐波那契数列。然后显示所有序列的总和。
该序列如下:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377
总和为 986。
以下是我的代码:
public class Fibonacci {
public static void main(String[] args) {
int n = 500, t1 = 0, t2 = 1;
while (t1 <= n)
{
System.out.print(t1 + " , ");
int sum = t1 + t2;
t1 = t2;
t2 = sum;
sum = t1 + t2;
}
System.out.println("");System.out.println("总和: "+(t2-1));
}
}
为了获得总和为 986,令我困惑的是如果我没有减去 1,我会得到 987。
英文:
The question goes like this Write a program to find the Fibonacci sequence from 0 to less than a 500. Then display the sum of all the sequences.
The sequence goes as follows:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377
with a total sum of 986.
Here is my code:
public class Fibonacci {
public static void main(String[] args) {
int n = 500, t1 = 0, t2 = 1;
while (t1 <= n)
{
System.out.print(t1 + " , ");
int sum = t1 + t2;
t1 = t2;
t2 = sum;
sum = t1 + t2;
}
System.out.println("");System.out.println("Sum: "+(t2-1));
}
}
To get a total sum of 986 what confuses me is I do get 987 if I haven't deducted 1.
答案1
得分: 3
你应该创建一个新的变量来保存你的和,初始值为0。你的代码正在使用声明为1的t2进行求和,这就是为什么你的总和中有一个+1。以下是修正后的代码:
public static void main(String []args){
int n = 500, t1 = 0, t2 = 1;
int total = 0;
while (t1 <= n)
{
total += t1;
System.out.print(t1 + " , ");
int sum = t1 + t2;
t1 = t2;
t2 = sum;
}
System.out.println("");
System.out.println("Sum: " + total);
}
英文:
you should create a new variable that holds your sum which initially starts at 0, your code is summing using t2 which is declared as 1, that's why you are having a +1 in your total, this code should work fine:
public static void main(String []args){
int n = 500, t1 = 0, t2 = 1;
int total=0;
while (t1 <= n)
{
total+=t1;
System.out.print(t1 + " , ");
int sum = t1 + t2;
t1 = t2;
t2 = sum;
sum = t1 + t2;
}
System.out.println("");System.out.println("Sum: "+(total));
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论