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

How to limit the amount of times a while loop runs? C++

本文关键字:c++ 运行 何限制 while 循环      更新时间:2023-10-16
#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;
    }
}

你必须添加一个计数器变量

int count=0;

当count变量达到3时,在while循环

中执行break语句

每次用户得到一个好的答案,你必须增加这个变量