c++ - 编写一个程序,计算并输出前 N 个奇数斐波那契数,以逗号和空格分隔。 N 从标准输入输入

标签 c++ fibonacci

我正在尝试编写这个程序,但我认为我在逻辑上犯了一些错误。 This is my code .好的,所以我运行一个循环来收集所有奇数,但我的最后一个数字是 0 或一些垃圾值。我是 C++ 的新手,我在 C 上花了更多时间,我假设我没有正确使用 vector 类,或者我的逻辑是垃圾。我花了很多时间,我就是想不通。我确信这是一个非常简单的解决方案,但我看不出我做错了什么。感谢您的宝贵时间!

main()
{
    int num; // how many odd numbers the user wants to see
    int first = 0; // first fibonacci number
    int second = 1; // second fibonacci number
    int next = 0; // basically the sum of the previous two numbers
    vector<int> holder; // a place to store the odd numbers
    holder.push_back(second); // adding 1, otherwise we would miss it
    cout << "How many ODD numbers would you like to see?:";
    cin >> num; // taking user's input

    int c, i;
    for (i = 0, i < num; i++) {
        next = first + second;
        first = second;
        second = next;
        if ((next % 2) != 0) {
            holder.push_back(next);
        }
    }

    for (c = 0; c < num + 1; c++) {
        cout << holder[c] << "," << " ";
    }

    return 0;
}

最佳答案

打印值时用这个循环替换

 for(c=0;c<num;c++){
                cout << holder[c] << "," << " ";
            }

关于c++ - 编写一个程序,计算并输出前 N 个奇数斐波那契数,以逗号和空格分隔。 N 从标准输入输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43341036/

相关文章:

c# - 在编程语言中扩展预增量运算符

c++ - 为什么我不能在派生类重写函数中调用 protected 虚拟基类函数?

k-斐波那契算法

c++ - 为什么在使用 `using directive` 时 ADL 不工作?

android - 我需要 Hyper-V 才能从 Visual Studio 2015 中调试我的 Android 应用程序吗?

c# - 在 C# 中递归打印斐波那契字符串

prolog - 为什么这个 Prolog Fibonacci 函数会导致 "instantiation_error"?

c# - 并行斐波那契数计算器

python - 在Python中获取斐波那契数列的无限循环

c++ - 通过 boost 获取本地时间