gpt4 book ai didi

c++ - 这段代码有什么问题?斐波那契数列

转载 作者:搜寻专家 更新时间:2023-10-31 02:06:53 25 4
gpt4 key购买 nike

它应该打印斐波那契数列直到一个位置,但它只打印 1 1 2,即使我要求的不仅仅是前三个元素。我该如何解决这个问题?

#include <iostream>
using std::cout;
using std::cin;

int main()
{
cout << "Enter a number: ";
int number;
cin >> number;
int count = 1;
int a = 1; //The first number of the Fibonacci's serie is 1
int b = 1; //The second number of the Fibonacci's serie is 2
while (count <= number)
{
if (count < 3)
cout << "1 ";
else
{
number = a + b; //Every number is the sum of the previous two
cout << number << " ";
if (count % 2 == 1)
a = number;
else
b = number;
}
count++;
}

return 0;
}

最佳答案

您在这里使用 number 作为循环迭代的最大次数:

while (count <= number)

但是在循环内,您使用与当前 Fib 值相同的变量来为每次迭代输出。

number = a + b;     //Every number is the sum of the previous two
cout << number << " ";

这导致循环提前终止。您需要为这两个不同的值选择不同的变量名称。

关于c++ - 这段代码有什么问题?斐波那契数列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49574810/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com