如何在C ++中使用STL查找数组元素的总和?
在这里,我们将看到如何找到数组所有元素的和。因此,如果数组类似于[12、45、74、32、66、96、21、32、27],则总和为:405。因此,这里我们必须使用accumulate()函数来解决此问题。该功能描述位于<numeric>头文件中。
示例
#include<iostream>
#include<numeric>
using namespace std;
int main() {
int arr[] = {12, 45, 74, 32, 66, 96, 21, 32, 27};
int n = sizeof(arr) / sizeof(arr[0]);
cout << "Array is like: ";
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
cout << "\nSum of all elements: " << accumulate(arr, arr + n, 0);
}输出结果
Array is like: 12 45 74 32 66 96 21 32 27 Sum of all elements: 405
热门推荐
1 训练狗狗基础
2 怎么训练狗狗笑
3 怎么训练狗狗卧下
4 上海狗狗训练基地
5 训练狗狗排便
6 狗狗基础训练
8 如何训练狗狗装死
9 狗狗站姿训练
10 狗狗训练用品
11 训练狗狗吧
12 狗狗要怎么训练
13 怎么训练狗狗玩球
14 训练狗狗唤回
15 狗狗训练躺下
16 狗狗训练指令
17 狗狗的训练技巧
18 狗狗不好训练