如何将此向量的元素相加?

How do I add the elements of this vector together?

本文关键字:元素 向量      更新时间:2023-10-16

我的代码的目的是将向量的元素一起加成一个整数。 这是针对欧拉项目的问题 #1:

https://projecteuler.net/problem=1

这是我的代码:

int main()
{
int max_count = 1000; //The upper bound
//Loop for filling vector
for (int i = 1; i <= max_count; ++i){
int counter[max_count];
if (counter[i] % 3 == 0|| counter[i] % 5 == 0){
vector <int> start_point = {};
start_point.push_back (counter[i]);
for (auto& n : start_point){
int sum_of_elems = 0;
sum_of_elems += n;
cout << sum_of_elems;
}   
}
}
return 0;
}

目前,我的代码正在输出以下内容,我无法弄清楚原因。

32766143547943202305202750000-4646761603276630-76434810000-76434582500-464677056327662448-4646770403276632766-46467703232766327666032766230586999-970904238-95777621723084852023084852032766-970904244-46467688032766230624075-970911300230826120-1916976912327663276623063434032766230634681-957776214230826120140084992032766-970911280327660003276603276630-4646761603276623058081332766-464676440327663276632766230831712230745153065793306031200003276623074515300-191647711200023084852023074515365793360036000002308224802307451533657937207200-46467616032766000023083171232766230595552230831712032766327660-46467619232766230577342230822480230829920000-46467616032766230822480230829960-46467264032766230540223001920409600-46467247232766327661920409600-46467220832766000000000011072962560230556921230818160-4646738403276619204096000000230510592-157214242200000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000192016926310000017014741627917691891969382724000000000000000000000000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

你在每个循环中重新初始化你的sum变量,所以你最终只打印了各个值。您还混合了循环和求和,这使您的代码复杂化;要么完全跳过vector(只有一个求和循环(,要么完全填充它,然后求和。

我不能给出更有用的建议,因为你在这里有很多相关的问题。您声明counter而不对其进行初始化,然后从未初始化的内存中读取以填充start_point

关键是,大多数变量需要在循环之外声明(因此它们不会在每个循环中从头开始重复重新初始化(,您的输出应该在循环之后,并且counter需要真实数据,因此您不会调用未定义的行为。

删除向量和其他不必要的变量,代码可以简化为:

#include <iostream>
int main()
{
int max_count = 1000; //The upper bound
int sumOfMultiples = 0;
for (int i = 1; i < max_count; ++i)
if (i % 3 == 0 || i % 5 == 0)
sumOfMultiples = sumOfMultiples + i;
std::cout << "Sum of  Multiples of 3 and 5 below 1000 is: " << sumOfMultiples << "n";      
return 0;
}

输出为:

Sum of  Multiples of 3 and 5 below 1000 is: 233168