如何将这个向量的元素加在一起?

时间:2018-09-27 01:06:23

标签: c++ vector cout

我的代码的目的是将向量的元素加在一起成为一个整数。这是针对Euler项目上的问题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-1572142422000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001920169263100000170147416279176918919693827240000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

2 个答案:

答案 0 :(得分:1)

您将在每个循环上重新初始化sum变量,因此最终只能打印各个值。您还将混合循环和求和,这使您的代码变得复杂。要么完全跳过vector(只是有一个求和循环),要么完全填充它,然后对其求和。

由于您遇到了许多相关问题,因此我无法提供更多有用的建议。您无需初始化就声明counter,然后从未初始化的内存中读取以填充start_point

要点是,您的大多数变量都需要在循环外部声明(因此,它们不会在 each 循环上从头开始反复重复初始化),您的输出应在循环之后,并且{{ 1}}需要真实的数据,因此您不会调用未定义的行为。

答案 1 :(得分:0)

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

#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