c++ - C++ 中的简单数组求和

标签 c++ sum

我是 C++ 的初学者,我有一个关于 C++ 中的简单求和代码的问题。

这是我的代码:

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;


int main()
{
    int n;
    int sum;
    int arr_i = 0;

    cin >> n;
    vector<int> arr(n);
    while (arr_i != n)
    {
        cin >> arr[arr_i];
        sum += arr[arr_i];
        //cout << sum << endl;
        if (arr_i == n - 1)
            cout << sum;
        arr_i++;
    }
    return 0;
}

如果 if 条件前没有“cout << sum”,输出不会打印正确答案。

我该如何解决这个问题?

最佳答案

您忘记将 sum 初始化为 0。

int sum = 0;

关于c++ - C++ 中的简单数组求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36510110/

相关文章:

MySQL对列的元素求和

Python:对列表中的 x 个元素求和

c# - 尝试从 C# 调用 C++ dll 时出现格式不正确的异常

c++ - 自包含从 std::enable_shared_from_this 继承的自身的 shared_ptr

c++ - 警告:使用 string::find_first_not_of 时从 int 截断为 char

c++ - 霍夫曼解码循环不迭代

c - 数组的递归和

mysql - 计数考虑 3 列的总和

c++ - OpenGL 中顶点数组缓冲区绘制的每个函数有什么作用?

algorithm - 最小列总和差异是多少?