简体   繁体   English

Java代码在斐波那契数列中显示错误的斐波那契数

[英]Java code shows wrong Fibonacci number in Fibonacci sequence

Im trying to make a Java code that displays the nth number in the Fibonacci sequence.我试图制作一个 Java 代码来显示斐波那契数列中的第 n 个数字。 For example if i put in 7, the code should show the number 8 since the 7th number in the Fibonacci sequence is 8.例如,如果我输入 7,代码应该显示数字 8,因为斐波那契数列中的第 7 个数字是 8。

But when I tried to make one, it shows the wrong number.但是当我试图制作一个时,它显示错误的数字。 For some reason, when i enter 7 it shows 13, and when I enter 1, it shows a 1 although I already stated that the first number is 0 in the code.出于某种原因,当我输入 7 时它显示 13,当我输入 1 时它显示 1,尽管我已经在代码中声明第一个数字是 0。

Scanner input = new Scanner(System.in);
System.out.print(“In: ”);
int n = input.nextInt();

int x = 0;
int y = 1;
int a;

for (int i = 1; i <= n; i++) {
  a = x + y;
  x = y;
  y = a;
}
System.out.print(x + " ");

I think the code for some reason ignores the first 0 which I dint understand.我认为代码出于某种原因忽略了我理解的第一个 0。 I would love some help, thank you.我想要一些帮助,谢谢。

Spandan is correct, if you modify your code to the below you will get the correct response all the way from 1 and up... Spandan 是正确的,如果您将代码修改为以下内容,您将从 1 开始一直得到正确的响应...

Note:笔记:

  1. The loop now iterates only as long as i<n which removes the unwanted result.循环现在仅在 i<n 时迭代,这会删除不需要的结果。

  2. The loop though will never produce the first number in the sequence (zero) as the first iteration can not be lower than one.虽然循环永远不会产生序列中的第一个数字(零),因为第一次迭代不能小于一个。 For that reason I have added the print of X before the loop runs the first time.出于这个原因,我在循环第一次运行之前添加了 X 的打印。

I hope this helps:)我希望这有帮助:)

import java.util.Scanner;

public class Fibonacci {
  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    System.out.print("Enter the number of terms: ");
    int n = input.nextInt();

    int x = 0;
    int y = 1;
    int a;

    System.out.print("Fibonacci sequence: ");
    System.out.print(x + " ");
     
    for (int i = 1; i < n; i++) {
      a = x + y;
      x = y;
      y = a;
      System.out.print(x + " ");
    }
  }
}

you will have to change the for condition to i <= n-1 and make a separate condition for when it is the first term.您必须将 for 条件更改为 i <= n-1 并为第一个术语设置一个单独的条件。 Fibonacci series is 1 1 2 3 5 8 13 but according to your code it is taking it as 1 2 3 5 8 13斐波那契数列是 1 1 2 3 5 8 13 但根据您的代码,它是 1 2 3 5 8 13

Try this试试这个

Scanner input = new Scanner(System.in);
System.out.print("In: ");
int n = input.nextInt();

int x = 0;
int y = 1;
int a;

for (int i = 1; i <= n; i++) {
  a = x + y;
  x = y;
  y = a;
}
System.out.print(x + " ");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM