如何在C中将所有数字添加到数组中?

新手上路,请多包涵

而不是打字

array[0] + array[1] //.....(and so on)

有没有办法将数组中的所有数字相加?我使用的语言是 c++,我希望能够用更少的输入来完成它,而不是我只是把它全部输入。

原文由 ShadowWesley77 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 820
2 个回答

尝试这个:

 int array[] = {3, 2, 1, 4};
int sum = 0;

for (int i = 0; i < 4; i++) {
    sum = sum + array[i];
}
std::cout << sum << std::endl;

原文由 Kiersten Jay Raymond 发布,翻译遵循 CC BY-SA 3.0 许可协议

关于 std::accumulate 用法再添加一点:

将 C 样式 数组 传递给函数 时,您 std::accumulateend start ---

例子:

 #include <numeric>
void outsideFun(int arr[], int n) {
    int sz = sizeof arr / sizeof arr[0]; // 1=decays to a ptr to the 1st element of the arr
    // int sum = accumulate(begin(arr), end(arr), 0); // Error:begin/end wouldn't work here
    int sum = accumulate(arr, arr + n, 0);            // 15 (Method 2 Only works!)
    std::cout << sum;
}

int main() {
    int arr[] = { 1,2,3,4,5 };
    int sz = sizeof arr / sizeof arr[0];           // 5
    int sum = accumulate(begin(arr), end(arr), 0); // 15 (Method 1 - works)
    int cum = accumulate(arr, arr + sz, 0);        // 15 (Method 2 - works)
    outsideFun(arr, sz);
}

原文由 SridharKritha 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题