0

从字面上看,我被问过这个问题“”斐波那契数列是 0, 1, 1, 2, 3, 5, 8, 13, ... ; 前两项是 0 和 1,之后的每一项都是前两项之和——即 Fib[n] = Fib[n – 1] + Fib[n – 2]。使用这些信息,编写一个 C++ 程序,计算斐波那契数列中的第 n 个数,其中用户在程序中交互输入 n。例如,如果 n = 6,则程序应显示值 8。”

感谢您对上一个问题的回答,我已将其放入我的完整代码中。我确实有一个循环,这意味着用户可以选择是否继续该程序。它早些时候工作,但现在什么也没有发生。任何人都可以对此有所了解吗?谢谢

{int N;

char ans = 'C';

while (toupper(ans) == 'C')
{
    cout<<"This program is designed to give the user any value of the Fibonacci Sequence that they desire, provided the number is a positive integer.";//Tell user what the program does

    cout<<"\n\nThe formula of the Fibonacci Sequence is;   Fib[N] = Fib[N – 1] + Fib[N – 2]\n\n"; //Declare the Formula for the User

    cout<<"Enter a value for N, then press Enter:"; //Declare Value that the User wants to see

    cin>>N;//Enter the Number

    if (N>1) {
            long u = 0, v = 1, t;

            for(int Variable=2; Variable<=N; Variable++)
            {
                t = u + v;
                u = v;
                v = t;
            } //Calculate the Answer

        cout<<"\n\nThe "<<N<<"th Number of the Fibonacci Sequence is: "<<t; //Show the Answer
    }

    if (N<0) {
        cout<<"\n\nThe value N must be a POSITIVE integer, i.e. N > 0"; //Confirm that N must be a positive integer. Loop.
    }
    if (N>100) {
        cout<<"\n\nThe value for N must be less than 100, i.e. N < 100. N must be between 0 - 100.";//Confirm that N must be less than 100. Loop.
    }
    if (N==0) {
        cout<<"\n\nFor your value of N, \nFib[0] = 0"; //Value will remain constant throughout, cannot be caculated through formula. Loop.
    }
    if (N==1) {
        cout<<"\n\nFor your value of N. \nFib[1]=1";//Value will remain constant throughout, cannot be caculated through formula. Loop.
    }

  cout << "\n\nIf you want to select a new value for N, then click C then press Enter. If you want to quit, click P then press Enter: ";
    cin >> ans;
}


return 0;

}

4

2 回答 2

1

你只需要在cout下面放两行。而且您不需要额外的 {},但这并没有什么坏处。

于 2013-03-03T20:42:24.603 回答
0

这是你的主循环:

for(int i=2; i<=N; i++)
{
    t = u + v;
    u = v;
    v = t;

    cout<<t<<"is your answer";
}

很明显,它会在循环中的每一次通过时打印出您的答案。

只需将打印移动到循环之外......在所有计算完成后,您只会看到它打印一次:

for(int i=2; i<=N; i++)
{
    t = u + v;
    u = v;
    v = t;
}
cout<<t<<"is your answer";

我在您的代码中看到的其他问题:

你声明一个函数:

unsigned long long Fib(int N);

但它从来没有被定义或使用过。为什么这个声明在这里?(去掉它)

您有一组多余的大括号:

else {
        {
            unsigned long long u = 0, v = [....]

您不需要立即使用大括号,然后再使用更多大括号。

于 2013-03-03T20:43:56.180 回答