C++ 如何将数组中的数字加在一起C++;

C++ 如何将数组中的数字加在一起C++;,c++,arrays,C++,Arrays,假设我有一个整数数组,它存储五个数字,我想把这些数字相加,然后把它们放到一个特定的变量中,我该怎么做呢。如果你有这个问题的答案,那么如果你能作出回应,我们将不胜感激。谢谢。这里有一个简单的整数求和代码: 另一种方法是使用: #包括 #包括 #包括 int main(){ 向量a={1,2,3,4,5}; 自动恢复=标准::累计(a.begin(),a.end(),0); std::coutfor(const auto&val:array)sum+=val;请记住将sum设置为一个足够大的数据

假设我有一个整数数组,它存储五个数字,我想把这些数字相加,然后把它们放到一个特定的变量中,我该怎么做呢。如果你有这个问题的答案,那么如果你能作出回应,我们将不胜感激。谢谢。

这里有一个简单的整数求和代码:

另一种方法是使用:

#包括
#包括
#包括
int main(){
向量a={1,2,3,4,5};
自动恢复=标准::累计(a.begin(),a.end(),0);

std::cout
for(const auto&val:array)sum+=val;
请记住将
sum
设置为一个足够大的数据类型,以存储总和,并记住将其初始化为0。这是否回答了您的问题?请参阅
#include <vector>
#include <iostream>

int main() {
    std::vector<int> a = {1, 2, 3, 4, 5};
    int res = 0;
    for (auto x: a)
        res += x;
    std::cout << res << std::endl;
    return 0;
}
15
#include <vector>
#include <iostream>
#include <numeric>

int main() {
    std::vector<int> a = {1, 2, 3, 4, 5};
    auto res = std::accumulate(a.begin(), a.end(), 0);
    std::cout << res << std::endl;
    return 0;
}