我收到一条错误,说主要是没有定义猜测。这是怎么回事? 编程旨在成为一个猜谜游戏
while只是因为main中定义的猜测而停止,但这会使计算机询问未经测试的输入。
#include <cstdlib>
#include <iostream>
#include <ctime>
using namespace std;
int nextGuess();
int main()
{
srand(time(0));
int number = rand() % 100 + 1;
cout <<" --GUESSING GAME-- \n You are to enter numbers, trying to guess rthe computer's number"<< endl;
int guess = nextGuess();
do
{
int guess = nextGuess();
if (guess > number)
cout <<"Your guess is to high."<< endl;
if (guess < number)
cout <<"Your guess is too low."<< endl;
if (guess == number)
cout <<"Good job, that's the number!"<< endl;
}
while (guess != number);
system("pause");
}
int nextGuess()
{
int guess = 0;
cout <<"Please enter a number:";
cin >> guess;
return guess;
}
**我会粘贴c提示,但不会复制。
答案 0 :(得分:1)
你可以拨打nextGuess
两次:一旦在循环之前,一旦在循环中。删除第一个调用,即循环之前的调用,但将变量guess
的声明保留在循环之外,并且不再在内部声明它。
答案 1 :(得分:1)
在你的while循环中,你正在重新定义变量guess。也许把它改成这样的东西:
int guess;
do
{
guess = nextGuess();
现在编写它的方式,循环中使用的变量猜测与while条件中使用的变量不同。
答案 2 :(得分:1)
您正在调用nextGuess
两次并在guess
块内重新声明变量do-while
。改为:
int guess;
do
{
guess = nextGuess();
if (guess > number)
cout <<"Your guess is to high."<< endl;
if (guess < number)
cout <<"Your guess is too low."<< endl;
if (guess == number)
cout <<"Good job, that's the number!"<< endl;
}
while (guess != number);
答案 3 :(得分:0)
使用while{}
代替do{}while
int guess = nextGuess();
while (guess != number)
{
guess = nextGuess();
if (guess > number)
cout <<"Your guess is to high."<< endl;
if (guess < number)
cout <<"Your guess is too low."<< endl;
if (guess == number)
cout <<"Good job, that's the number!"<< endl;
}
答案 4 :(得分:0)
这是因为你两次致电nextGuess
。只需在循环外声明变量,然后调用其中的函数即可。
#include <cstdlib>
#include <iostream>
#include <ctime>
using namespace std;
int nextGuess();
int main()
{
srand(time(0));
int number = rand() % 100 + 1;
cout <<" --GUESSING GAME-- \n You are to enter numbers, trying to guess rthe computer's number"<< endl;
int guess;
do{
guess = nextGuess();
if (guess > number)
cout <<"Your guess is to high."<< endl;
if (guess < number)
cout <<"Your guess is too low."<< endl;
if (guess == number)
cout <<"Good job, that's the number!"<< endl;
}
while (guess != number);
return 0;
}
int nextGuess()
{
int guess = 0;
cout <<"Please enter a number:";
cin >> guess;
return guess;
}