zoukankan      html  css  js  c++  java
  • C语言实现一个简单的猜数字游戏

    简单的猜数字游戏!

    /*
     最经典的猜数字游戏的例子来展示条件结构在程序中的作用,今天看到另外一种猜数字的玩法,也挺有趣: 这个游戏由三个人一起玩,
     一个人做主持人,心中默想一个1到100之间的数字,然后由其他两个人轮流猜,每次猜测之后,主持人就说出猜测的这个数比他心中
     的数字是大还是小,然后另外一个人根据这个信息继续猜测,如此轮流,最后谁猜中就算谁输了。(算赢了也可以) 这是一个相互挖坑
     让对方跳的过程,特别是最后几步,猜测范围越来越小,真是步步惊心,稍不留意,就踩到对方挖的坑里去了。
    
     ============================================================================
     Name        : numbergame1.c
     Author      : lixiaolong
     Version     : v1.0
     Copyright   : Your copyright notice
     Description : number of game in C, Ansi-style
     Encoding time:2013年10月31日11:09:41
     ============================================================================
     */
    
    #include <stdio.h>
    #include <time.h>
    #include <stdlib.h>
    #include <stdbool.h>
    #include <ctype.h>
    int main()
    {
        srand( time(NULL) );//随机数种子
    
        while(true)
        {
            int min = 1;
            int max = 100;//初始范围
            int count = 0;//猜测次数
            const int target = rand()%max + 1;//产生随机数的目标数
            while(true)
            {
                int guess = 0;
                printf("please input a number between %d and %d
    ",min,max);
                fflush(stdin);//清空输入缓存,以便不影响后面输入的数。比如你逐个输入字符,他帮你缓冲掉你每输入一个字符后面所敲的回车键。否则回车也会被当成字符保存进去。
                scanf("%d",&guess);  // 获取猜测的数字
                ++count;
    
                if(guess < min || guess > max) //超出范围
                {
                    printf("the input is out of %d - %d
    ",min,max);
                    continue;
                }
                else
                {
                    if(target == guess) //猜中
                    {
                        printf("YOU WIN!
    you have guessed %d times in total.
    ",count);
                         break;
                    }
                    else if(target > guess) //目标比猜的数字大
                    {
                        min = guess;
                        printf("the target is larger than %d
    ",guess);
                    }
                    else  //目标比猜的数字小
                    {
                        max = guess;
                        printf("the target is less than %d
    ",guess);
                    }
                }
            }
            //本轮游戏结束,是否继续
            printf("Do you want to play again?(Y - yes,N - no)
    ");
            fflush(stdin);
            char c = 'Y';
            scanf("%c",&c);
            if(toupper(c) != 'Y')
            {
                break;
            }
        }
    
        return 0;
    }

    这个程序扮演了主持人出数字并进行判断的角色,可以和朋友(女朋友更合适)两个人一起玩,也可以一个人玩,看看那次猜测的次数最少。

  • 相关阅读:
    围棋GO
    Android 四大组件------Activity
    android studio----设备兼容
    android UI开发--------Action Bar
    开发调试工具----DDMS
    RxJava的使用
    Atlas框架
    Android studio上git的使用
    AS上git的使用与遇到的问题
    picasso-安卓的图片下载缓存库
  • 原文地址:https://www.cnblogs.com/kingshow123/p/cnumbergame.html
Copyright © 2011-2022 走看看