要求 You can use the "return 0;" statement inside an "if" block to exit the program when the answer is correct. Using this will make your code much simpler, and there is no need to use "nested if" statements.
题目要求是 在判断正确后就直接返回0,”nested if"是指嵌套if,但是代码里面并没有嵌套if,你老师可能看错了吧。
还有就是把第二个while里面的if(gameTrack==3)去掉,直接把分支里的代码移出来就可以了,这样更简洁。
#include<iostream>
#include<time.h>
#include<stdlib.h>
using namespace std;
int main()
{
int secretNumber;
int guessNumber; int gameTrack = 0;
cout << "Welcome to the number guessing game.\n";
cout << "You have at most 3 chances to guess a secret number from 1 to 10.\n";
while (true)
{
srand(time(0));
secretNumber = rand() % 10 + 1;
cout << "Enter a number from 1 to 10.\n";
gameTrack = 0;
while (gameTrack != 3) {
cin >> guessNumber;
if (guessNumber == secretNumber)
{
cout << "Congratulation, correct!\n";
return 0;
}
else if (guessNumber > secretNumber)
{
gameTrack += 1;
cout << "Not correct, too high try again.\n";
}
else if (guessNumber < secretNumber)
{
gameTrack += 1;
cout << "Not correct, too low try again.\n";
}
}
cout << "You have reached your third trials. The correct number is " << secretNumber << "\n";
}
}
想要3次结束后 或者 猜对数字后 停止运行 ,直接把最外面的while(true)语句注释掉就可以了,另外你的代码有点问题。
参考如下:
#include <iostream>
#include <time.h>
using namespace std;
int main()
{
int secretNumber, gameTrack, guessNumber;
int playGamesCount = 0;
int win = 0;
int loose = 0;
cout << "Wlecome to the number guessing game.\n";
cout << "For each game,you have at most 3 chances to guess a secret number from 1 to 10." ;
srand(time(0)); //执行一次就可以了,不需要放在while循环里
//while (true) //如果判断正确,输入0,或者猜3次都错误,就退出程序的话,就把这一句注释掉就可以了
{
//srand(time(0));
secretNumber = rand() % 10 + 1;
cout << "\nEnter a number from 1 to 10. Enter 0 to exit:";
gameTrack = 0;
playGamesCount += 1;
while (gameTrack != 3) {
cin >> guessNumber;
if (guessNumber == secretNumber) {
cout << "\nCongratulation,correct!Let's start a new secret number.";
win += 1;
break;
}
else if (guessNumber == 0) {
break;
}
else //if (guessNumber != secretNumber) //这个if语句不需要了
{
gameTrack += 1;
cout << "Not correct,try again:";
}
} //while end
//这个if语句放在这里,否则loose+=1就不执行了,也不需要用else
if (gameTrack == 3) {
cout << "\nNot correct.You have reached your third trials. The correct number is " << secretNumber;
loose += 1;
//break; //如果猜错了就结束程序
}
if (guessNumber == 0) {
//break; //输入0 也结束程序
}
}
cout << "Game Summary:\n";
cout << "Total games:" << playGamesCount << "\n";
cout << "Total game wins:" << win << "\n";
cout << "Total game losses:" << loose << "\n";
return 0;
}
You can use the "return 0;" statement inside an "if" block to exit the program when the answer is correct. Using this will make your code much simpler, and there is no need to use "nested if" statements.
Use only the "if else if" statements to process the first and second answer. Do not use "nested if" statements because it will make code more complicated. Use "if else" to process the third answer.