gpt4 book ai didi

c++ - C++ 中的 Play again 选项不适用于数字猜谜游戏

转载 作者:行者123 更新时间:2023-12-01 14:36:42 26 4
gpt4 key购买 nike

当用户输入“Y”重试时,游戏运行但只给用户 1 次尝试而不是 3 次尝试。程序第一次运行时运行良好,尝试了 3 次。我猜我的循环有问题,它不会重置尝试次数?让我知道是否有任何其他方法可以编写我的代码以使其更清晰/更好。非常感谢。

#include <iostream>
#include <cstdlib>
#include <time.h>
using namespace std;

int guessNum;
int randomNum;
int Tries = 0;

int startGame()
{
cout << "Number: ";
cin >> guessNum;

return guessNum, Tries;
}

int main(int a, int b)
{
while (true) {

a = guessNum;
b = Tries;
char ans;

// Random number
srand(time(NULL));
randomNum = rand() % 20 + 1;

// Introduction
cout << "Guess a number between 1 to 20. You have three attempts." << endl;

do
{
startGame();

if (guessNum < randomNum)
{
cout << "Wrong! It is too low." << endl;
}

else if (guessNum > randomNum)
{
cout << "Wrong! It is too high." << endl;
}

Tries++;
}

while (guessNum != randomNum && Tries < 3);

if (guessNum != randomNum) // Wrong answer & run out of tries
{
cout << "Oops.. All attempts used. The answer is " << randomNum << endl;
}

else if (guessNum == randomNum) // User guessed correct number
{
cout << "Yes! You are correct!" << endl;
}

cout << "Try again?";
cin >> ans;
cin.ignore();

if (ans == 'N')
{
cout << "Thanks for playing!";
break;
}

}
}

已编辑 V1


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

int guessNum;

int startGame()
{
cout << "Number: ";
cin >> guessNum;

return guessNum;
}

int main()
{
while (true) {

int randomNum;
int Tries = 0;
char ans;

// Random number
srand(time(NULL));
randomNum = rand() % 20 + 1;

// Introduction
cout << endl << "Guess a number between 1 to 20. You have three attempts." << endl;

do
{
startGame();

if (guessNum < randomNum)
{
cout << "Wrong! It is too low." << endl;
}

else if (guessNum > randomNum)
{
cout << "Wrong! It is too high." << endl;
}

Tries++;
}

while (guessNum != randomNum && Tries < 3);

if (guessNum != randomNum) // Wrong answer & run out of tries
{
cout << "Oops.. All attempts used. The answer is " << randomNum << endl;
}

else if (guessNum == randomNum) // User guessed correct number
{
cout << "Yes! You are correct!" << endl;
}

cout << "Try again? Y/N: ";
cin >> ans;
cin.ignore();

ans = toupper(ans);
if (ans == 'N')
{
cout << endl << "Thanks for playing!";
break;
}

else
{
Tries = 0;
}

}
}

最佳答案

实际上,您的程序有几个缺陷。

首先,如果你想知道为什么游戏在第一个游戏之后表现出意想不到的方式,你没有在玩游戏后将 Tries 设置回 0。

而且,int startgame() 应该只返回一个变量。您正在尝试同时返回 guessnum 和 Tries。第一个游戏按预期运行的唯一原因是你使用了全局变量,这也被认为是一种不好的做法(如果你没有任何正当理由使用它,一些公司可能会解雇你)。

此外,您从 main 调用中获得了两个 int 函数参数,这是无效的。 (主函数签名应该是 int main(void) 或 int main(int argc, char* argv[]))。我很惊讶编译器没有捕捉到这个错误。

而变量(int a, int b)其实并没有用到。当您发现未使用的变量时,为了便于维护,通常最好删除它们。

关于c++ - C++ 中的 Play again 选项不适用于数字猜谜游戏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62549816/

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