好吧,这是一个简单的项目,它会做所有事情,因为它应该减去它应该退出的时间。

我尝试了许多不同的方法,包括goto语句,我尝试了if循环,但是除了错误什么都没有。当前的代码没有错误,只是我不知道要去哪里退出。不必花哨,这只是我的第二个程序

// C// Guess My Number
// The classic number guessing game

#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;
int main()
{

srand(static_cast<unsigned int>(time(0)));  //seed random number generator

int secretNumberE = rand() % 10 + 1;
int secretNumberM = rand() % 100 + 1;// random number between 1 and 100
int secretNumberH = rand() % 1000 + 1;
int tries = 0;
int guess;
char play;


{
cout << "\tWelcome to Guess My Number\n\n";
START:
cout << "Difficulty Levels\n\n";
cout << "1 - Easy\n";
cout << "2 - Normal\n";
cout << "3 - Hard\n\n";


int choice;
cout << "Choice: ";
cin >> choice;

switch (choice)
{
case 1:
cout << "You picked Easy.\n";
do
{
    cout << "Enter a guess 1-10: ";
    cin >> guess;
    ++tries;

    if (guess > secretNumberE)
    {
        cout << "Too high!\n\n";
    }
    else if (guess < secretNumberE)
    {
        cout << "Too low!\n\n";
    }
    else
    {
        cout << "\nThat's it! You got it in " << tries << " guesses!\n";
    }

} while (guess != secretNumberE);
std::cout << "Do you want to play again y/n? ";
cin >> play;
if ( play = 'y' ){
goto START;
}
else if (play = 'n')
{
cout << " Thank you for playing. ";
return 0;
}
break;
case 2:
cout << "You picked Normal.\n";
do
{
    cout << "Enter a guess 1-100: ";
    cin >> guess;
    ++tries;

    if (guess > secretNumberM)
    {
        cout << "Too high!\n\n";
    }
    else if (guess < secretNumberM)
    {
        cout << "Too low!\n\n";
    }
    else
    {
        cout << "\nThat's it! You got it in " << tries << " guesses!\n";
    }

} while (guess != secretNumberM);
std::cout << "Do you want to play again y/n? ";
cin >> play;
if ( play = 'y' ){
goto START;
}
else if (play = 'n')
{
cout << " Thank you for playing. ";
return 0;
}
break;
case 3:
cout << "You picked Hard.\n";
do
{
    cout << "Enter a guess 1-10: ";
    cin >> guess;
    ++tries;

    if (guess > secretNumberH)
    {
        cout << "Too high!\n\n";
    }
    else if (guess < secretNumberH)
    {
        cout << "Too low!\n\n";
    }
    else
    {
        cout << "\nThat's it! You got it in " << tries << " guesses!\n";
    }

} while (guess != secretNumberH);
std::cout << "Do you want to play again y/n? ";
cin >> play;
if ( play = 'y' ){
goto START;
}
else if (play = 'n')
{
cout << " Thank you for playing. ";
return 0;
}
break;

default:
cout << "You made an illegal choice.\n";
goto START;
return 0;
}}}

最佳答案

if ( play = 'y' ){
goto START;
}
else if (play = 'n')
{
cout << " Thank you for playing. ";
return 0;
}


第一个if始终为true,因为您使用的是赋值运算符而不是相等运算符。您需要使用==比较两个值。

关于c++ - C++退出循环无法正常工作,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18753055/

10-10 23:08
查看更多