c++ - 如何限制 while 循环运行的次数? C++

标签 c++ while-loop

#include <iostream>
#include <cmath>
#include <ctime>
#include <cstdlib>
using namespace std;

int main( )
{
    int number1; 
    int number2;
    int answer; 
    srand(time(0));
    number1= rand()%10+1;
    number2= rand()%10+1;
    cout<< number1 <<" + " << number2 << endl; 

    cin>> answer; 

    if(number1 + number2 == answer) {
        cout << "correct"<< endl; 

    }
    else {
        cout << "Incorrect" << endl; 
        cout << "Answer:" << number1 + number2;
    }

    while(number1+number2==answer) {

    }
    return 0;
}

我正在尝试制作一个程序,向用户询问一个简单的数学问题。在这最后一步中,用户必须正确回答三个问题,然后循环结束。

如果用户回答错误,循环将继续。我的问题是我该怎么做?我对如何设置循环以使程序正常工作感到困惑。

最佳答案

根据您的评论,您应该有一个 while 循环,其中包含三个问题和一个计算正确答案数的计数器。如果用户答对了所有三个问题,您就可以跳出循环,否则您将再次提出所有三个问题。所以这样的事情可能对你有用:

int total = 0;

while (1) {
    cin >> answer;

    if (number1 + number2 == answer) {
        cout << "correct"<< endl;
        ++total;
    }
    else {
        cout << "Incorrect." << endl;
    }

    // include two more questions with if and else statements

    // check if all three answers correct
    if (total == 3) {
        cout << "You got every answer right!" << endl;
        break;
    }
    else {
        cout << "You got " << 3 - total << " questions wrong.";
        total = 0;
    }
}

关于c++ - 如何限制 while 循环运行的次数? C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33271974/

相关文章:

java - 如何创建一个从 ArrayList 的一行到另一行拆分每一行的循环?

c++ - fstream中的write函数在Windows 10上会导致bug

Java - 通过 HashMap

python - 如何创建一个自下而上的合并排序函数来改变输入列表?

c - 跳出这个 while 循环

java - do while 内部的计算无法正常工作

c++ - 如何组合输出流,以便同时输出多个位置?

c++ - 如何使用 Visual Studio C++ 编译器?

c++ - Qt 5.4 静态构建在 Visual Studio 2013 中产生 "unresolved external symbol"链接错误

c++ - 如何在 JUCE 项目中获得 "go to definition"?