基本程序实现由电脑随机生成一个位于1~100的数,用户输入开始猜数(最多猜十次),猜对了就退出程序并询问用户是否再来一局,猜大了,报错输出too big,猜小了,报错输出too small。最多猜十次,十次过后没猜出来则结束,并询问用户是否再来一局。
一.基于输入随机数种子生成随机数。
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<math.h>
#include<stdlib.h>//引用rand函数
int main()
{
int magic;
int guess;
int ret;//用于保存函数scanf()的返回值
int counter = 0;
char reply;
unsigned int seed;//定义一个无符号整形变量
do {
counter = 0;
printf("please enter seed:");
scanf("%u", &seed);
srand(seed);//为函数rand()设置随机数种子(为了得到随机数组)
magic = rand() % 100 + 1;//使随机数的范围在1~100间
do {
printf("please guess a magic numble:");
ret = scanf("%d", &guess);
while (ret != 1)//若输入非法字符则重新输入
{
while (getchar() != '\n');//清除输入缓冲区的非法字符
printf("please guess a magic number:");
ret = scanf("%d", &guess);
}
counter++;
if (guess < magic)
{
printf("wrong,too small\n");
}
else if (guess > magic)
{
printf("wrong,too big\n");
}
else
{
printf("right\n");
}
} while (guess != magic && counter < 10);//判断退出条件最多猜十次和猜对的时候退出)
printf("counter=%d\n", counter);
printf("do you want to continue(Y/N or y/n)?");
scanf(" %c", &reply);//%c前面有个空格(避免前面输入到缓冲区的回车键被当成有效字符赋给reply)
} while (reply == 'Y' || reply == 'y');
return 0;
}
二.利用时间time()函数实现对随机数的选用。
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<math.h>
#include<stdlib.h>//引用rand函数
#include<time.h>
int main()
{
int magic;
int guess;
int ret;//用于保存函数scanf()的返回值
int counter = 0;
char reply;
do {
counter = 0;
printf("please enter seed:");
srand(time(NULL));//l利用电脑时间为函数rand()设置随机数种子(为了得到随机数组)
magic = rand() % 100 + 1;//使随机数的范围在1~100间
do {
printf("please guess a magic numble:");
ret = scanf("%d", &guess);
while (ret != 1)//若输入非法字符则重新输入
{
while (getchar() != '\n');//清除输入缓冲区的非法字符
printf("please guess a magic number:");
ret = scanf("%d", &guess);
}
counter++;
if (guess < magic)
{
printf("wrong,too small\n");
}
else if (guess > magic)
{
printf("wrong,too big\n");
}
else
{
printf("right\n");
}
} while (guess != magic && counter < 10);//判断退出条件最多猜十次和猜对的时候退出)
printf("counter=%d\n", counter);
printf("do you want to continue(Y/N or y/n)?");
scanf(" %c", &reply);//%c前面有个空格(避免前面输入到缓冲区的回车键被当成有效字符赋给reply)
} while (reply == 'Y' || reply == 'y');
return 0;
}