如何解决这个问题以编写一个使用 while 循环来计算前 n 个斐波那契数的程序

发布于 2024-12-07 04:20:26 字数 969 浏览 1 评论 0原文

我是 C++ 编程新手,有点迷失。这是我应该做的事情和我的代码。关于该做什么有什么想法吗?

编写一个程序,使用 while 循环计算前 n 个斐波那契数。回想一下数学中斐波那契数列的以下定义:

斐波那契数 Fn 定义如下。 F0 为 1,F1 为 1,Fi+2 = Fi + Fi+1(i = 0, 1, 2, ...)。换句话说,每个数字都是前两个数字的总和。前几个斐波那契数是 1、1、2、3、5、8 和 13。

程序应提示用户输入 n(斐波那契数的个数)并将结果打印到屏幕上。如果用户输入的 n 值无效(n <= 0),则打印一条错误消息并要求用户重新输入 n(n 的输入验证循环)。这必须是一个循环,而不是像实验 2 那样的 if 语句。

输出应类似于以下内容:

输入要计算的斐波那契数列数:3 前 3 个斐波那契数是: 1 1 2

#include <iostream>
using namespace std;
int main()
{
    int f0 = 0, f1  = 1,f2= 2, i = 0, n;
    cout << "Enter the number of Fibonacci numbers to compute: ";
    cin >> n;
    if ( n <= 0)
    {
        cout <<"Error: Enter a positive number: ";
        return 1;
    }
    while ( i < n){
        f2 = f0 + f1;
        i++;
    }

    cout << "The first " << n << " Fibonacci numbers are: " << endl;
    cin >> n;
    return 0;
}

I am new to C++ programming and I am a bit lost. Here is what I am suppose to do and my code. Any ideas on what to do?

Write a program that uses while loops to calculate the first n Fibonacci numbers. Recall from math the following definition of the Fibonacci sequence:

The Fibonacci numbers Fn are defined as follows. F0 is 1, F1 is 1 and Fi+2 = Fi + Fi+1 for i = 0, 1, 2, ... . In other words, each number is the sum of the previous two numbers. The first few Fibonacci numbers are 1, 1, 2, 3, 5, 8, and 13.

The program should prompt the user for n (the number of Fibonacci numbers) and print the result to the screen. If the user enters an invalid value for n (n <= 0), print an error message and ask the user to re-enter n (an input validation loop for n). This MUST be a loop, not an if statement like Lab 2.

The output should be similar to the following:

Enter the number of Fibonacci numbers to compute: 3
The first 3 Fibonacci numbers are:
1 1 2

#include <iostream>
using namespace std;
int main()
{
    int f0 = 0, f1  = 1,f2= 2, i = 0, n;
    cout << "Enter the number of Fibonacci numbers to compute: ";
    cin >> n;
    if ( n <= 0)
    {
        cout <<"Error: Enter a positive number: ";
        return 1;
    }
    while ( i < n){
        f2 = f0 + f1;
        i++;
    }

    cout << "The first " << n << " Fibonacci numbers are: " << endl;
    cin >> n;
    return 0;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

梦归所梦 2024-12-14 04:20:26
 while ( i < n){
        f2 = f0 + f1;
        i++;
    }

看到这个循环,这就是问题所在,因为这是作业,我不会确切地告诉问题是什么,拿笔和纸,开始执行你的语句,特别是这个循环,你会发现你的错误。只是提示,斐波那契数是前两个斐波那契数的总和。

 while ( i < n){
        f2 = f0 + f1;
        i++;
    }

See this loop, this is where the problem is, since this is homework, i'll not tell exactly what the problem is, take a pen and paper, and start executing your statements, specially this loop, you'll find your error. Just a hint, Fibonacci number is the sum of previous two fibonacci numbers.

作妖 2024-12-14 04:20:26

你的f2=f0+f1是对的。但是,您应该注意,当您递增 i 时,f2 将变为 f1,而 f1 将变为 f0

如果你这样命名它们,那就更有意义了:

int f_i_minus_2 = 0, f_i_minus_1 = 1, f_i;

现在,想象

f_i = f_i_minus_1+f_i_minus_2;

i 是 3。你已经写了:

f[3] = f[2]+f[1]

当你递增 i 时,你必须有:

f[4] = f[3]+f[2]

f_i 放在 f_i_minus_1 的位置,f_i_minus_1 放在 f_i_minus_2 的位置。

(看这个

f[3] = f[2] + f[1]
 |       |
  \_____  \____
        \      \
f[4] = f[3] + f[2]

:)

所以在计算 f_i 后你需要两次赋值:

f_i_minus_2 = f_i_minus_1;
f_i_minus_1 = f_i;

请注意,我首先将 f_i_minus_2 更改为 f_i_minus_1 因为第二次赋值破坏了f_i_minus_1 的值。

You got the f2=f0+f1 right. However, you should note that when you increment i, then f2 becomes f1 and f1 becomes f0.

If you name them like this, it would make more sense:

int f_i_minus_2 = 0, f_i_minus_1 = 1, f_i;

and you would have

f_i = f_i_minus_1+f_i_minus_2;

Now, imagine i is 3. You have written:

f[3] = f[2]+f[1]

When you increment i, you must have:

f[4] = f[3]+f[2]

That is f_i is put in the place of f_i_minus_1 and f_i_minus_1 is put in the place of f_i_minus_2.

(Look at this:

f[3] = f[2] + f[1]
 |       |
  \_____  \____
        \      \
f[4] = f[3] + f[2]

)

So you need two assignments after computing f_i:

f_i_minus_2 = f_i_minus_1;
f_i_minus_1 = f_i;

Note that I first changed f_i_minus_2 to f_i_minus_1 because the second assignment destroys the value of f_i_minus_1.

雾里花 2024-12-14 04:20:26

根据维基百科,你的定义是错误的。 F0=0,F1=1,F2=1,F3=2,...

http://en。 wikipedia.org/wiki/Fibonacci_number

假设维基百科是正确的,你的循环基本上是

int i = 0, f, fprev;
while( i < n )
{
    if( i == 0 )
    {
        f = 0;
        fprev = 0;
    }
    else if( i == 1 )
    {
        f = 1;
    }
    else
    {
        int fnew = f + fprev;
        fprev = f;
        f = fnew;
    }
    i++;
}

According to wikipedia, your definition is off. F0=0, F1=1, F2=1, F3=2, ...

http://en.wikipedia.org/wiki/Fibonacci_number

Assuming wikipedia is right your loop is basically

int i = 0, f, fprev;
while( i < n )
{
    if( i == 0 )
    {
        f = 0;
        fprev = 0;
    }
    else if( i == 1 )
    {
        f = 1;
    }
    else
    {
        int fnew = f + fprev;
        fprev = f;
        f = fnew;
    }
    i++;
}
墨小沫ゞ 2024-12-14 04:20:26

正如其他人指出的那样,因为您从不修改 f0f1
循环中,f2 不会依赖于循环的次数
环形。因为无论如何你都必须输出最后的所有数字,
为什么不尝试将它们保存在一个数组中。我会初始化前两个
手动值,然后循环直到我有足够的值。

(使用 STL 可以很好地完成此操作:

//  After having read n...
std::vector<int> results( 2, 1 );
while ( results.size() < n )
    results.push_back( *(results.end() - 1) + *(results.end() - 2));

但是,我不确定这是否是您的讲师所需要的。
我相当怀疑他希望你自己做一些索引。只是
请记住,如果您手动初始化前两个值,您的
索引必须从 2 开始,而不是从 0 开始。)

另一件事:您发布的规范说您应该循环 if
用户输入非法值。这实际上有点棘手:如果
用户输入的内容不是 int(例如“abc”),然后 1)
std::cin 将保持错误状态(并且所有进一步的输入都将失败)
直到清除(通过调用 std::cin.clear()),并且非法
字符不会从流中提取,所以你的下一次尝试
将失败,直到您删除它们。 (我建议>>进入
std::string 为此;这将删除所有内容,直到下一个白色
空格。)并且永远不要访问您>>写入的变量,直到
如果输入失败,您已经检查了流是否失败。如果
输入失败,输入的变量未被修改。如果像这里一样,你
还没有初始化它,那么任何事情都有可能发生。

最后(我确信这超出了你的任务范围),你真的做到了
需要做一些事情来检查溢出。超过某一点,
你的输出或多或少会变得随机;最好停下来
在这种情况下您要放弃的输出。

As others have pointed out, since you never modify f0 and f1 in the
loop, f2 isn't going to depend on the number of times through the
loop. Since you have to output all of the numbers at the end anyway,
why not try keeping them in an array. I'd initialize the first two
values manually, then loop until I had enough values.

(This can be done quite nicely using the STL:

//  After having read n...
std::vector<int> results( 2, 1 );
while ( results.size() < n )
    results.push_back( *(results.end() - 1) + *(results.end() - 2));

I'm not sure that this is what your instructor is looking for, however.
I rather suspect that he wants you to to some indexing yourself. Just
remember that if you initialize the first two values manually, your
index must start at 2, not at 0.)

Another thing: the specification you post says that you should loop if
the user enters an illegal value. This is actually a little tricky: if
the user enters something that isn't an int (say "abc"), then 1)
std::cin will remain in error state (and all further input will fail)
until cleared (by calling std::cin.clear()), and the illegal
characters will not be extracted from the stream, so your next attempt
will fail until you remove them. (I'd suggest >>ing into an
std::string for this; that will remove everything until the next white
space.) And don't ever access the variable you >>ed into until
you've checked the stream for failure—if the input fails. If the
input fails, the variable being input is not modified. If, as here, you
haven't initialized it, then anything can happen.

Finally (and I'm sure this goes beyond your assignment), you really do
need to do something to check for overflow. Beyond a certain point,
your output will become more or less random; it's better to stop and
output that you're giving up in this case.

能否归途做我良人 2024-12-14 04:20:26

如果您有兴趣,可以使用更好的计算方法

If you are interested, there are better ways to calculate it.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文