gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 02:18:34 24 4
gpt4 key购买 nike

#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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com