【发布时间】:2015-07-19 16:26:51
【问题描述】:
我被要求创建一个随机数猜谜游戏,该游戏生成一个随机的 5 位数字,然后提示用户猜数字。然后游戏会生成反馈以帮助用户做出更好的猜测(假设他们第一次没有猜对)。例如,如果随机数数组和用户猜测数组中的第一个数字都匹配,则游戏输出 1,如果猜测数组中的第一个数字与随机数数组中的第一个数字不匹配,但与其他数字中的一个匹配,游戏输出 2;如果猜测数组中的第一个数字与随机数数组中的任何数字都不匹配,则游戏输出 0(即,如果随机数数组 = 31350 并且用户猜测为 32010,则反馈将打印为 10221)。我想我已经完成了大部分工作,但反馈部分无法正常工作。输出是一个 20 多位的数字,无论输入如何,它都表示猜到了正确的数字。到目前为止,这是我的代码。
#include "stdafx.h"
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
bool checkGuess(int numberToGuess[], int guess[], int size);
int _tmain(int argc, _TCHAR* argv[])
{
const int DIGITS = 5;
int numberToGuess[DIGITS]; //declares array holding the random string of numbers
int guess[DIGITS]; //declares array holding the user guesses
srand(time(NULL)); //random seed
cout << "Welcome to the number guessing game!\n";
cout << "In this game you will try to guess a random 5 digit number" << endl;
for (int i = 0; i < DIGITS; i++) //loop to generate the random number
{
numberToGuess[i] = rand() % 9 + 1;
}
do
{
cout << "Please enter your guess: " << endl; //prompts user for their guess
cin >> guess[1, 2, 3, 4, 5];
bool comparedGuess = checkGuess(numberToGuess, guess, 5);
if (comparedGuess == false)
{
for (int i = 0; i < DIGITS; i++)
{
if (guess[i] == numberToGuess[i])
{
guess[i] = 1;
}
else if (guess[i] == numberToGuess[0, 1, 2, 3, 4])
{
guess[i] = 2;
}
else
{
guess[i] = 0;
}
}
}
for (int i = 0; i < DIGITS; i++)
{
cout << guess[i];
}
cout << endl;
}
while (guess[DIGITS] != numberToGuess[DIGITS]);
cout << "You guessed it correctly!" << endl;
system("pause");
return 0;
}
bool checkGuess(int numberToGuess[], int guess[], int size) //function to compare user guess to random number
{
if (guess[size] == numberToGuess[size])
{
return true;
}
else
{
return false;
}
}
【问题讨论】:
-
numberToGuess[i] = rand() % 9 + 1;永远无法生成 0。试试numberToGuess[i] = rand() % 10; -
很好,我已经更改了它,但反馈系统仍然无法正常工作。
-
cin >> guess[1, 2, 3, 4, 5];无法按照您想要的方式工作。编译器应该告诉你。同上guess[i] == numberToGuess[0, 1, 2, 3, 4] -
@user4581301 尽管我认为这可能是我的问题,但编译器没有给我任何错误,您对我如何解决这个问题有什么建议吗?
-
默认警告级别可能太低。不知道如何在视觉工作室中打开它。最简单的解决方法是读入 std::string 而不是 char 数组,然后测试该字符串是否正好是 5 个字符。