c++ - vector +for+if

标签 c++ if-statement for-loop vector addition

好的,所以我们的目标是为斐波那契数本身编写一些代码,然后用这些数字找出哪些数字,然后将这些特定数字加在一起。一切正常,除了我尝试并尝试找出一种将数字相加的方法,但我总是遇到错误,并且对如何将它们相加感到困惑。我查看了其他地方,但他们都要求提供 vector 中的所有元素。不是从 if 语句中提取的特定内容。

附注我知道系统(“暂停”)很糟糕,但我尝试了其他一些选项,但有时它们有效,有时则不起作用,我不确定为什么。如cin.get()。

P.S.S 我对自己的程序编程也很陌生,所以就我所知而言,我的资源有限,并且会欣赏任何可以“改进”我的程序以使其工作更流畅的方法。我也很好地接受批评,所以请这样做。

#include "../../std_lib_facilities.h"

int main(){
    vector<int>Fibonacci;
    int one = 0;
    int two = 1;
    int three = 0;
    int i = 0;
    while (i < 4000000){
        i += three;
        three = two + one; one = two; two = three;
        cout << three << ", ";
        Fibonacci.push_back(three);
        //all of the above is to produce the Fibonacci number sequence which starts with 1, 2 and    adds     the previous one to the next so on and so forth.
        //bellow is my attempt and taking those numbers and testing for evenness or oddness and then adding the even ones together for one single number.
    }
    cout << endl;
    //go through all points in the vector Fibonacci and execute code for each point
    for (i = 0; i <= 31; ++i)   
        if (Fibonacci.at(i) % 2 == 0)//is Fibonacci.at(i) even? 
            cout << Fibonacci.at(i) << endl;//how to get these numbers to add up to one single sum

    system("pause");
}

最佳答案

用手做就可以了。即循环整个数组并跟踪累积和。

int accumulator = 0;  // Careful, this might Overflow if `int` is not big enough.
for (i = 0; i <= 31; i ++)  {
    int fib = Fibonacci.at(i);
    if(fib % 2)
        continue;
    cout << fib << endl;//how to get these numbers to add up to one single sum
    accumulator += fib;
}

// now do what you want with "accumulator".

小心这个大型数学系列,它们爆炸得非常快。就您的情况而言,我认为计算大约适用于 32 位整数。最好使用 64 位或更好的、适当的 BigNum 类。

关于c++ - vector +for+if,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22663393/

相关文章:

android - Unity3d 安卓插件问题

c# - 写出列表的特定行

java - 将字符串与字符串值进行比较

python - 如何将每一列数据与其他每一列数据进行比较

java - 使用扫描仪读取文本,存储在数组中并使用每个循环输出大写Java

c++ - 大小写切换是这样工作的吗?

c++ - 避免 C++ 模板中的成员冲突

c++ - 可变参数模板函数 : specialize head/tail and empty base case

Java Interest Calculator 无法编译,不知道为什么

java - For循环(元素:collection) not making permanent change