Fork me on GitHub

C语言使用rand()函数随机生成数,让用户猜数字游戏简单小程序。使用if,do while

使用随机数生成一个1-100的随机数,让用户输入数字去猜测此数并且记录猜测的次数。

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <time.h>
 4 
 5 int main(){
 6     srand(time(0));            //先设置种子
 7     int number=rand()%100+1;    //然后产生随机数    +1是1-100之间的数 如果用户输入的是0则加1
 8     int count=0;        //定义计数变量 
 9     int a=0;        
10     
11     printf("我已经想好一个1-100之间的数了\n");
12     do{
13     printf("请你猜这个数:\n");
14     scanf("%d",&a);
15     count++;
16     if(a>number){
17         printf("你输入的数大了\n"); 
18     }else if(a<number){
19         printf("你数入的数小了\n");     
20     }
21     
22     }while(a!=number);     
23     printf("太棒了,你用了%d次就猜对了答案 \n",count);
24     return 0;
25 }

运行结果

posted @ 2020-04-26 13:02  云源  阅读(1521)  评论(0编辑  收藏  举报
湖南云源网络科技有限公司 www. ysource.cn 版权所有   ICP证:湘ICP备18004366号
  邮箱:2536201485@qq.com   CSDN博客地址:https://blog.csdn.net/qq_32885621 有事您Q我