写一个猜数字的游戏,要求随机生成一个1-20之间的数字,然后用户输入自己猜的数字, 然后输出猜大了,还是猜小了,或者猜中了,如果没有猜中,一直让用户才猜下去,猜中为止。
tips:
srand((unsigned)time(NULL));//设置随机种子
n=rand()%(X);//n为0-X之间的随机数。
代码如下:
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int main(int *argc, char *argv[])
{
int i;
int j;
int flag = 0;
srand((unsigned)time(NULL));
j = rand() % 20 + 1;//例如取3-5之间的随机数 %2 +3,其中2=5-3 ,3是起始位置
printf("%d\n", j);//n为0-X之间的随机数
printf("温馨提示,随机数系统已经随机生成数值,请输入你想要猜测的数字,祝你好运:\n");
while (1) {
scanf_s("%d",&i);
if (i == j)
{
printf("猜中了!!\n");
flag = 1;
}
if (j < i)
{
printf("猜大了!!\n");
printf("请继续猜!!\n");
}
if(j > i)
{
printf("猜小了!!\n");
printf("请继续猜!!\n");
}
}
return 0;
}