如何获得从0到小于500的斐波那契数列的和。

huangapple go评论69阅读模式
英文:

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 &lt;= n)
        {
            System.out.print(t1 + &quot; , &quot;);
            int sum = t1 + t2;
            t1 = t2;
            t2 = sum;
            sum = t1 + t2;
            }
             System.out.println(&quot;&quot;);System.out.println(&quot;Sum: &quot;+(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 &lt;= n)
    {
        total+=t1;
        System.out.print(t1 + &quot; , &quot;);
        int sum = t1 + t2;
        t1 = t2;
        t2 = sum;
        sum = t1 + t2;
     }
        
     System.out.println(&quot;&quot;);System.out.println(&quot;Sum: &quot;+(total));
 }

huangapple
  • 本文由 发表于 2020年10月12日 19:14:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/64316766.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定