我的代码被困在C++的无限环中。
我正在尝试使用一段时间循环来计算3个输入成绩的平均值,但是我无法进入下一个年级,因为循环继续前进而没有给我进入下一个年级的机会。
#include<iostream>
using namespace std;
int main()
{
int grade = 0;
int count = 0;
int total = 0;
cout << "Enter grade: ";
cin >> grade;
while (grade != -1)
{
total = total + grade;
count = count + 1;
cout << "Enter next grade: ";
cin >> grade;
}
int(average) = total / 3;
cout << "Average: " << int(average) << endl;
system("pause");
}
I am trying to use a while loop to calculate the average of 3 inputted grades, but I can not enter the next grade as the loops keep on going without giving me the chance to enter the next grade.
#include<iostream>
using namespace std;
int main()
{
int grade = 0;
int count = 0;
int total = 0;
cout << "Enter grade: ";
cin >> grade;
while (grade != -1)
{
total = total + grade;
count = count + 1;
cout << "Enter next grade: ";
cin >> grade;
}
int(average) = total / 3;
cout << "Average: " << int(average) << endl;
system("pause");
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我用整数测试了您的代码,它可以正常工作。
如果您仅将INT作为输入,最好是放一些东西来检查输入类型。使用
cin.fail()
检查用户输入INT以外的其他任何内容。例如:
我从 https://www.codegrepper.com/code-examples/cpp/how+to+check+type+type+input+input+cin+cin +c%2B%2B%2B
href =“ https://stackoverflow.com/questions/18728754/checking-cin-input-stream-produces-an-integer”>检查CIT CIN INTUP流可以产生整数
I tested your code with integer and it works fine.
If you only take int as input, the best is to put something to check the input type. Use
cin.fail()
to check if user input anything other than int.for example:
which I refer from https://www.codegrepper.com/code-examples/cpp/how+to+check+type+of+input+cin+c%2B%2B
and here as well Checking cin input stream produces an integer