0

推測がメインで定義されていないというエラーが表示されます。どうしたの?プログラムは推測ゲームとして設計されています

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 プロンプトを貼り付けますが、コピーされません。

4

5 に答える 5

1

2 回呼び出して、ブロック内で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

nextGuess2 回呼び出します: ループのに 1 回、ループの内側に 1 回。ループの前の最初の呼び出しを削除しますが、変数の宣言guessをループの外に保持し、ループ内で再度宣言しないでください。

于 2013-11-14T13:08:40.083 に答える
1

while ループでは、変数の推測を再定義しています。たぶん、次のように変更します。

int guess;
do
{    
    guess = nextGuess();

あなたが今書いたように、ループで使用される変数の推測は、while 条件で使用される変数と同じではありません。

于 2013-11-14T13:09:04.873 に答える
0

それは、あなたがnextGuess2 回電話をかけているからです。ループの外側で変数を宣言してから、ループ内で関数を呼び出すだけで十分です。

#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 に答える