计算机随机出一个数,然后用户猜,如果猜对了,则输出结果,如果猜错了,输出猜大或者小了。
#include<stdio.h>
#include<stdlib.h>
int main()
{
int magic;/*计算机想的数*/
int guess;/*用户猜出的数*/
magic=rand()%100+1;
printf("please input the number of you guess\n");
scanf("%d",&guess);
if(guess>magic)
{
printf("wrong,too big!\n");
}
else if(guess<magic)
{
printf("wrong, too small\n");
}
else
{
printf("right\n");
printf("the number id:%d\n",magic);
}
return 0;
}
本程序只能猜一次。所以修改下,直到猜对为止。程序如下
#include<stdio.h>
#include<stdlib.h>
int main()
{
int magic;/*计算机想的数*/
int guess;/*用户猜出的数*/
int count=0;/*记录猜的次数*/
magic=rand()%100+1;
do{
printf("please input the number of you guess\n");
scanf("%d",&guess);
count++;
if(guess>magic)
{
printf("wrong,too big!\n");
}
else if(guess<magic)
{
printf("wrong, too small\n");
}
else
{
printf("right\n");
}
}while(guess!=magic);
printf("the number is:%d\n",magic);
printf("the times is :%d\n",count);
return 0;
}
本程序虽然做到了直到猜对为止,但是每次机器想的都是一样的。因为rand()函数是个伪随机数。
为了修改下。设置随机化数字,用time函数。
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int main()
{
int magic;/*计算机想的数*/
int guess;/*用户猜出的数*/
int count=0;/*记录猜的次数*/
srand(time(NULL));
magic=rand()%100+1;
do{
printf("please input the number of you guess\n");
scanf("%d",&guess);
count++;
if(guess>magic)
{
printf("wrong,too big!\n");
}
else if(guess<magic)
{
printf("wrong, too small\n");
}
else
{
printf("right\n");
}
}while(guess!=magic&&count<10);/*最多猜10次*/
printf("the number is:%d\n",magic);
printf("the times is :%d\n",count);
return 0;
}
程序可以多次猜,如果猜数结束还可以进行下一次
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int main()
{
int magic;/*计算机想的数*/
int guess;/*用户猜出的数*/
int count=0;/*记录猜的次数*/
char reply;
srand(time(NULL));
do{
magic=rand()%100+1;
do{
printf("please input the number of you guess\n");
scanf("%d",&guess);
count++;
if(guess>magic)
{
printf("wrong,too big!\n");
}
else if(guess<magic)
{
printf("wrong, too small\n");
}
else
{
printf("right\n");
}
}while(guess!=magic&&count<10);/*最多猜10次*/
printf("the number is:%d\n",magic);
printf("the times is :%d\n",count);
printf("do you want to continue(Y/N or y/n)\n");
scanf(" %c",&reply);
}while((reply=='Y')||(reply=='y'));
return 0;
}
1244

被折叠的 条评论
为什么被折叠?



