• C语言猜数字游戏


    问题:

      编写一个猜数字的游程序,任意给一个1—100之间的整数,程序应能迅速的猜出此数是多少,每猜完一次数之后询问是否继续,若回答是则继续做猜数游戏,若回答否,则结束程序运行。

    分析:

      rand()是“伪随机数”产生函数,注意,是“伪随机数”,而不是随机数,如果每次srand()给的参数值都相同,那么rand()产生的序列就是相同的,time(NULL)返回的是从某年的1月1日0时0分0秒到系统当前时间所经过的秒数,所以如果不是同一秒钟以内多次运行程序的话,time(NULL)的返回值一定是不同的,用这样的方式来产生相对比较随机的序列。在C语言头文件<stdlib.h>中包含标准库函数srand(),设置产生随机数的种子。程序员可以在程序开始时自行设置种子的数值。

     1 #include<stdio.h>
     2 #include<stdlib.h>
     3 #include<time.h>
     4 main()
     5 {
     6     int a,b;
     7     char c;
     8     srand(time(NULL));
     9     a=1+(rand()%100);
    10     printf("I have a number between 1 and 100.
    Can you guess my number?
    Please type your first guess.
    ");
    11     scanf("%d",&b);
    12     while(b)
    13     {
    14     if(b==a)
    15     {
    16         printf("Excellent! You guessed the number!
    Would you like to play again(y or n)?");
    17         scanf(" %c",&c);     //%c前面的空格不能少!用以隔离以前输入的回车符 
    18         switch(c){
    19         case 'y':
    20             printf("I have a number between 1 and 100.
    Can you guess my number?
    Please type your first guess.
    ");
    21             scanf("%d",&b);
    22             break;
    23         case 'n':
    24             break;
    25         }
    26     }
    27 
    28     while(b<a)
    29     {
    30         printf("Too low.Try again.");
    31         scanf("%d",&b);
    32     }
    33 
    34     while(b>a)
    35     {
    36         printf("Too high.Try again.");
    37         scanf("%d",&b);
    38     }
    39     }
    40 }
  • 相关阅读:
    《C++标准程序库》 第6章 STL Container
    《C++语言99个常见编程错误》
    单例模式
    《C++标准程序库》 第7章 Iterator Adapters
    Shell颜色封装(C++)
    《改善C++程序的150个建议》
    OpenCV之图片的创建、保存和复制
    XMLDOM对象方法:对象事件
    三国中最精辟的十句话
    中国十大名茶及鉴别方法
  • 原文地址:https://www.cnblogs.com/geziyu/p/8734659.html
Copyright © 2020-2023  润新知