0

我收到一个错误,说猜测没有在 main.xml 中定义。这是怎么回事?prog被设计成一个猜谜游戏

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;
}

** Id 粘贴 c 提示,但不会复制。

4

5 回答 5

1

您正在调用nextGuess两次并guessdo-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);
于 2013-11-14T13:11:30.297 回答
1

您确实调用nextGuess了两次:一次循环之前,一次在循环内。删除第一个调用,即循环之前的调用,但将变量的声明保留在guess循环外部,不要在内部再次声明它。

于 2013-11-14T13:08:40.083 回答
1

在您的 while 循环中,您正在重新定义变量guess。也许把它改成这样:

int guess;
do
{    
    guess = nextGuess();

按照您现在编写的方式,循环中使用的变量guess 与while 条件中使用的变量不同。

于 2013-11-14T13:09:04.873 回答
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;
}
于 2013-11-14T13:15:13.507 回答
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;
}
于 2013-11-14T13:08:39.083 回答