简单猜数游戏的实现

2016-11-23  本文已影响0人  琼Kevin

1,项目说明


猜数字的游戏,系统随机生成一个数,用户输入一个数进去,直到猜对为止用一个选项让玩家继续玩下去

2,项目流程

1,输入:rand(),随机产生的一个数,srand(time(NULL)),撒下种子
          用户输入一个数,进行比较,并且是输出猜数是大是小
2,处理:while(1);直到相等输出字符N退出循环
        for(;count>0;cont--),三次循环机会
3,输出:猜数的结果

3,项目效果图

![DW_N1){54P8]4(4WM{Q{VTJ.jpg](https://img.haomeiwen.com/i2619158/40dd73f8d88620a6.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

4,项目源码

// Ex4.5  A Modified Guessing Game
#include <stdio.h>
#include <stdlib.h>                   
#include <time.h>                           // For time() function
#include <ctype.h>                          // I added this for toupper()
//#include <stdbool.h>                        // I added this for true

int main(void)
{
  int chosen = 0;                           // The lucky number
  int guess = 0;                            // Stores a guess
  const int max_tries = 3;                  // The maximum number of tries
  int limit = 20;                           // Upper limit for pseudo-random values
  char answer = 'N';

  srand(time(NULL));                        // Use clock value as starting seed
  printf("\nThis is a guessing game.\n");

  while(true)                              
  {
    chosen = 1 + rand() % limit;             // Random int 1 to limit
    printf("I have chosen a number between 1 and 20 which you must guess.\n");

    for(int count = max_tries ; count > 0 ; --count)
    {
      printf("\nYou have %d tr%s left.", count, count == 1 ? "y" : "ies");
      printf("\nEnter a guess: ");          // Prompt for a guess 
      scanf("%d", &guess);                  // Read in a guess

      // Check for a correct guess
      if(guess == chosen)
      {
        printf("\nCongratulations. You guessed it!\n");
        break;                              // End the program
      }
      else if(guess < 1 || guess > 20)      // Check for an invalid guess
        printf("I said the number is between 1 and 20.\n ");
      else
        printf("Sorry, %d is wrong. My number is %s than that.\n",
                            guess, chosen > guess ? "greater" : "less");
    }
    printf("\nYou have had three tries and failed. The number was %ld\n", chosen);
    printf("Do you want to play again (Y or N)?");
    scanf(" %c", &answer);
    if(toupper(answer) != 'Y')
      break;

  }
  return 0;
}



上一篇 下一篇

猜你喜欢

热点阅读