gpt4 book ai didi

c++ - vector + for + if

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

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

附言我知道 system("pause") 不好,但我尝试了一些其他选项,但有时它们有效,有时它们无效,我不确定为什么。比如 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 位或更好的 propery BigNum 类。

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

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