有没有人知道为什么这会一直崩溃,当我加入平均值时它开始崩溃

时间:2017-10-24 13:17:41

标签: c++ average

有谁知道为什么这会一直崩溃,当我平均添加时它开始崩溃。如果有人知道PLZ帮助我新编码,这对我来说很复杂,谢谢

#include <iostream>
#include <vector>
using namespace std;
int main()
{
    int integers;
    int average;
    int sum = 0;
    vector<int> numbers;
    cout << "Please enter in integers and enter 0 to stop: ";
    while (cin >> integers) {
        if (integers == 0) {
            sum = sum + integers;
            break;
        }
        numbers.push_back(integers);

    }
    int y = numbers.size();
    for (int i = 0; i < y; i++) {
        cout << numbers[i] << " ";
        average = (sum / integers);
        cout << "The average is: " << average << endl;
        return 0;
    }
}

1 个答案:

答案 0 :(得分:3)

当您到达for循环时,integers变量的值为0。在这个声明中:

average = (sum / integers);

您除以0因此导致undefined behavior和/或异常,具体取决于实施方式。这就是说你没有正确计算sumaverage