我的代码被困在C++的无限环中。

发布于 2025-02-01 05:39:48 字数 568 浏览 2 评论 0原文

我正在尝试使用一段时间循环来计算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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

清欢 2025-02-08 05:39:48

我用整数测试了您的代码,它可以正常工作。

如果您仅将INT作为输入,最好是放一些东西来检查输入类型。使用cin.fail()检查用户输入INT以外的其他任何内容。

例如:

while(cin.fail()) {
    cout << "Error" << endl;
    cin.clear();
    cin.ignore(256,'\n');
    cout << "Please enter grade:"
    std::cin >> grade;
}

我从 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:

while(cin.fail()) {
    cout << "Error" << endl;
    cin.clear();
    cin.ignore(256,'\n');
    cout << "Please enter grade:"
    std::cin >> grade;
}

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文