简单随机数生成器无限循环

时间:2020-01-29 22:34:10

标签: c++

我在上课时遇到了麻烦,因为当我尝试使用srand()函数时它无限选择了一个新的随机数。坚持下去,我将不胜感激。我试图获取代码以随机选择一个数字,然后用户必须猜测数字是多少。但是,每当用户输入错误时,我的程序随机代码都会更改。

// Game Module

void header();
int menuchoice();
void storytime();
int enter = 0;
int number = 0;
void exit();

void Game2();
int Random_Number();
int selection = 0;

int main() {
  // Declarations
  int game1 = 0;
  int game2 = 0;
  int game3 = 0;
  int choice = 0;

  header();

  menuchoice();

  return 0;
}

void header() {
  cout << "Welcome to the Sprengel Game Emporium!" << endl << endl;
}

int menuchoice() {
  int choice;

  cout << "Press 1 and Enter to Play Game 1 - Story Time" << endl;
  cout << "Press 2 and Enter to Play Game 2 - Guess the Random Number!" << endl;
  cout << "Press 3 and Enter to Play Game 3" << endl;
  cout << "Press 0 to EXIT" << endl;

  cin >> choice;

  if (choice == 1) {
    storydata();
  } else if (choice == 2) {
    Game2();
  } else if (choice == 3) {
    Game3();
  } else if (choice > 3) {
    cout << "Invalid Option, please choose again." << endl;
    menuchoice();
  } else if (choice == 0) {
    exit();
  }
  return 0;
}

// GAME 2

void Game2() {
  cout << "Welcome to Game 2!" << endl;
  cout << "This game randomly generates a number! To win, you have to "
          "correctly guess the number between 1 and 10!"
       << endl;
  cout << Random_Number();
}

int Random_Number() {
  srand(time(NULL));

  int selection = 0;
  int number = rand() % 10 + 1;
  cout << number << endl;
  cout << "Please guess a number between 1 and 10!" << endl;
  cin >> selection;

  if (selection == number) {
    int choose = 0;
    cout << "You are correct!" << endl;
    cout << "Press 1 to Play Again, Press 2 to return to the Game Menu, and "
            "Press 3 to Exit the Game"
         << endl;
    cin >> choose;
    if (choose == 1) {
      Random_Number();
    } else if (choose == 2) {
      menuchoice();
    } else if (choose == 3) {
      exit();
    }
  } else if (selection > number) {
    cout << "Incorrect! Try guessing lower." << endl;
    Random_Number();
  } else if (selection < number) {
    cout << "Incorrect! Try guessing higher." << endl;
    Random_Number();
  }
  return choice;
}

void Game3() { cout << "Welome to Game 3!" << endl; }

void exit() {
  cout << endl << endl;
  cout << "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" << endl << endl;
  cout << "Cya Later! Thanks for Playing!" << endl << endl;
  cout << "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" << endl;
}

0 个答案:

没有答案
相关问题