有谁知道为什么这会一直崩溃,当我平均添加时它开始崩溃。如果有人知道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;
}
}
答案 0 :(得分:3)
当您到达for
循环时,integers
变量的值为0
。在这个声明中:
average = (sum / integers);
您除以0
因此导致undefined behavior和/或异常,具体取决于实施方式。这就是说你没有正确计算sum
和average
。