【问题标题】:How to write a loop based on user input in C++?如何在 C++ 中根据用户输入编写循环?
【发布时间】:2017-11-01 02:27:31
【问题描述】:

如何根据用户输入运行循环?

例子:

我问用户要计算多少学生的成绩。

如果用户输入 2 个学生,那么我会要求用户输入考试、作业、测验等的成绩...

程序计算出第一个学生的成绩后,如何为第二个学生再次运行循环?

我尝试使用 while 循环,但它只是进入无限循环。

我所做的是:

cout << "number of student you want to calculate grade for" << endl; 

cin >> student; 

while (student) { 
... 
... 
... 
... 
} 

当我运行它时,它会进入无限循环。

【问题讨论】:

标签: c++ loops


【解决方案1】:

您需要确保在循环内减少学生,同时检查是否还有任何学生需要获取信息。

while(student > 0){ // check if any students left
    // your code to get student information
    student -= 1; // decrement students
} 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-11
    • 1970-01-01
    • 1970-01-01
    • 2020-10-11
    • 1970-01-01
    • 2014-03-19
    • 1970-01-01
    • 2021-05-27
    相关资源
    最近更新 更多