例4 关于程序结构
这是一个进行猜数字的交互应用程序,程序运行后自动产生一个1~100的随机数,游戏开始程序产生所猜数字,并给出相应,游戏者根据程序相应再猜数字,最后得出答案。
#include <stdio.h>
#include <stdlib.h> //应用srand函数
#include <ctype.h> //应用toupper函数
#include <time.h> //使用当前时钟做种子
int main()
{
int count, //猜数次数
number, //随机被猜数
guess; //所猜数字
char yes='Y';
printf("\nNow let us play the game.\nGuess the number:");
while(yes=='Y')
{
count=0;
srand((unsigned)time(NULL));
number=rand()%100+1;
do{
do{
printf("\nInput an integer number(1-100):");
scanf("%d",&guess);
}while(!(guess>=1&&guess<=100));
if(guess<number)
printf("\nYour answer is LOW,try again.");
if(guess>number)
printf("\nYour answer is HIGHT,try again.");
count++;
if(count==15)
{
printf("\nThis is the %d times!Think it hard next!",count);
exit(0); //15次退出
}
}while(!(guess==number));
if(count<=7)
{
printf("\nYou hace got it in %d times.\n",count);
printf("\nCongretulations!\n");
}
else
{
printf("\nYou got it in %d times.\n",count);
printf("\nI bet you can do it better\n");
}
printf("\n NEXT?(Y/N):");
scanf("%c",&yes);
yes=toupper(yes);
}
return 0;
}
笔记
C语言中的随机函数random,可是random函数并不是ANSIC标准,所以说,random函数不能在gcc,vc等编译器下编译通过。