为什么我的数组会打印一些内存垃圾?

问题描述 投票:0回答:1

这是我的代码:

#include <iostream>

using namespace std;

class Sumator {
public:
    int s = 0;
    int Numbers[10];
    int sum = 0;
    void sumall() {
        cout << "How many numbers do you want to enter into the array?" << endl;
        cin >> s;
        for (int i = 0; i < s; i++) {
            cout << "enter numbers into the table";
            cin >> Numbers[i];
        }
    }

    int n = sizeof(Numbers) / sizeof(Numbers[0]);

    void Suma()
    {
        for (int i = 0; i < n; i++){
            sum += Numbers[i];
        }
        cout << "here is your sum of the numbers from the array:  "<< sum;
    }
};

int main()
{
    Sumator Su;
    Su.sumall();
    Su.Suma();
    return 0;
}

我知道向量会是一个更好的解决方案,但我想找出我的代码中的问题所在。

c++
1个回答
0
投票

Suma 计数错误,因为“数字”未初始化为零,因此“s”元素之后的所有内容都是垃圾。

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.