简单猜数游戏的实现

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](http://upload-images.jianshu.io/upload_images/2619158-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;
}



最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,455评论 25 708
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,973评论 19 139
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,250评论 4 61
  • 独居第一周,赶上公司也搬家,作为部门对接人忙前忙后基本五一三天假也占去大半。终于享受了一个四月自由的下午一觉睡到傍...
    _levi阅读 505评论 1 0
  • 江南多雨,萦怀的缠绵,一个人等公交的时候如果下雨,撑着伞行走在轻盈如絮的烟雨里,不自觉得异想天开,总觉得会遇见龙猫...
    糖不甜了阅读 582评论 6 7