如何在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
热门推荐
2 红丝绒戚风蛋糕
3 夹心小甜点
4 南瓜甜点
6 粘米粉蒸蛋糕
7 酸奶华夫饼
9 红柚鸡蛋糕
10 葡萄干蛋糕
11 紫薯蛋糕卷
13 纸杯裱花小蛋糕
14 果酱奶酪蛋糕
15 日式樱花蔓越莓大福
16 草莓蛋糕卷
17 卡仕达长崎杯子蛋糕