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

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

How to get the sum of Fibonacci sequence 0 to less than 500

问题

以下是您要翻译的内容:

问题是这样的:编写一个程序,找到从0到小于500的斐波那契数列。然后显示所有序列的总和。
该序列如下:

  1. 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377

总和为 986

以下是我的代码:

  1. public class Fibonacci {
  2. public static void main(String[] args) {
  3. int n = 500, t1 = 0, t2 = 1;
  4. while (t1 <= n)
  5. {
  6. System.out.print(t1 + " , ");
  7. int sum = t1 + t2;
  8. t1 = t2;
  9. t2 = sum;
  10. sum = t1 + t2;
  11. }
  12. System.out.println("");System.out.println("总和: "+(t2-1));
  13. }
  14. }

为了获得总和为 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:

  1. 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:

  1. public class Fibonacci {
  2. public static void main(String[] args) {
  3. int n = 500, t1 = 0, t2 = 1;
  4. while (t1 &lt;= n)
  5. {
  6. System.out.print(t1 + &quot; , &quot;);
  7. int sum = t1 + t2;
  8. t1 = t2;
  9. t2 = sum;
  10. sum = t1 + t2;
  11. }
  12. System.out.println(&quot;&quot;);System.out.println(&quot;Sum: &quot;+(t2-1));
  13. }
  14. }

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。以下是修正后的代码:

  1. public static void main(String []args){
  2. int n = 500, t1 = 0, t2 = 1;
  3. int total = 0;
  4. while (t1 <= n)
  5. {
  6. total += t1;
  7. System.out.print(t1 + " , ");
  8. int sum = t1 + t2;
  9. t1 = t2;
  10. t2 = sum;
  11. }
  12. System.out.println("");
  13. System.out.println("Sum: " + total);
  14. }
英文:

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:

  1. public static void main(String []args){
  2. int n = 500, t1 = 0, t2 = 1;
  3. int total=0;
  4. while (t1 &lt;= n)
  5. {
  6. total+=t1;
  7. System.out.print(t1 + &quot; , &quot;);
  8. int sum = t1 + t2;
  9. t1 = t2;
  10. t2 = sum;
  11. sum = t1 + t2;
  12. }
  13. System.out.println(&quot;&quot;);System.out.println(&quot;Sum: &quot;+(total));
  14. }

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:

确定