使用生成随机数的函数,让程序生成一个随机数,记录在变量number当中: 定义一个负责记录次数的变量count初始值为0; 让用户输入一个数字存入变量guess当中; 猜的次数count每次增加1,即count++或count+1 判断guess和number的大小关系,如果guess大,就输出“你猜的数大了”,否则就输出“你猜的数小了” 如果guess和number的数不相等,就一直猜数,直到猜中为止,猜中后显示“太好了,你用了多少次猜到了答案是多少!” 随机数取值:
#include <stdlib.h>
#include <time.h>
srand((unsigned)time(NULL)); a = rand()%100+1;
代码:
#include<stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int number,count=0,guess;
srand((unsigned)time(NULL));
number=rand()%100+1;
printf("请输入你猜的数");
scanf("%d",&guess);
while(number!=guess)
{
if(number>guess)
printf("你输入的数小于随机数,请重新输入:");
else
printf("你输入的数大于随机数,请重新输入:");
count++;
scanf("%d",&guess);
}
count++;
printf("你用%d次猜到了这个数",count);
}