【问题标题】:how to add the numbers inside an array together C++ [duplicate]如何将数组中的数字加在一起C++ [重复]
【发布时间】:2021-03-08 14:40:49
【问题描述】:

假设我有一个整数数组并存储五个数字,我想将这些数字加在一起并将它们放入某个变量中,我该怎么做。如果您对此有答案,那么如果您能回复,将不胜感激。谢谢。

【问题讨论】:

标签: c++ arrays


【解决方案1】:

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

Try it online!

#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

另一种方法是使用std::accumulate:

Try it online!

#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;
}

【讨论】:

    猜你喜欢
    • 2021-06-04
    • 1970-01-01
    • 2015-06-01
    • 2020-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多