思特维工作室 | 网罗设计、考试资源 http://www.soitway.com http://www.soitway.net

您现在的位置: 思特维工作室 >> 考试资源 >> 等级考试 >> 正文

用c语言编写猜数游戏

作者:admin    教程来源:本站原创    点击数:    更新时间:2008-6-30

用c语言编写一个猜数游戏,由计算机想一个数请人猜,如果猜对了,则结束游戏..猜错继续猜,并提示是高了还是低了..并统计猜的次数.反应人猜的水平.

 

代码一:(未测试)

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define Range 100
int guess(int k){
int input;
printf("请输入数字:\t");
scanf("%d",&input);
if(input==k)return 1;
if(input>k)return -1;
if(input<k)return -2;
}
void score(int time){
if(time<5){printf("恭喜! Score: 100\n");return;}
if(time>=5&&time<11){printf("超过时间~ Score: 80\n");return;}
else{printf("笨! Score: 50\n");}
}
int main(){
int aim;
srandom((unsigned)time(0));
aim = random()%Range;
int i,flag;
i=flag=0;
while(flag!=1){
flag=guess(aim);
if(flag==-1)printf("大了!\n");
if(flag==-2)printf("小了!\n");
if(flag==1)printf("恭喜答对! 此数是:%d\n",aim);
i++;
}
score(i);
return 0;
}

 

代码二:(已测试好了, 并全部程序编译通过.每一行有详细说明)
/*#include "stdafx.h"*/

#include "time.h"/*时间头文件*/
#include "stdlib.h" /*标准库包含文件*/
#include "stdio.h" /*标准IO包含文件*/
main() /*主程序入口*/
{
char c; /*定义一个字符型的变量, 用来输入要猜的数*/
clock_t start,end; /*定义两个时钟变量,实际上就是一个长整形, 它在time.h中定义为:typedef long clock_t;*/
time_t a,b; /*定义两个时间变量,也是长整形*/
double var; /*定义临时变量, 用于计算猜出数字共花了多少时间*/
int i,guess; /*定义变量来保存随机数和玩家猜的数*/
srand(time(NULL)); /*设置随机数*/
printf("do you want to play it.('y' or 'n') \\n"); /*提示输入y或n开始或结束*/
loop: /*重复输入时程序定位点*/
while((c=getchar())=='y') /*接受键盘输入,是y则一直执行*/
{
i=rand()%100; /*随机数模100为产生随机数.*/
printf("\\nplease input number you guess:\\n"); /*提示输入要猜的数字*/
start=clock(); /*记下开始时程序共使用了多少个CPU即处理器时钟,Calculates the processor time used by the calling process*/
a=time(NULL); /*记下开始时的时间, 格式如年月日时分秒*/
scanf("%d",&guess); /*输入要猜的数字*/
while(guess!=i) /*如果输入的数不等于产生的随机数*/
{
if(guess>i){/*要猜的数大于随机数*/
printf("please input a little smaller.\\n"); /*提示输入小一点的数.*/
scanf("%d",&guess);/*输入小一点的数*/
}
else {/*否则*/
printf("please input a little bigger.\\n"); /*请你输入大一点的数,这句和上句是叫输入与随机数一样大的数.*/
scanf("%d",&guess);/*输入大一点的数.*/
}
}
/*过了上面这个}, 表示找到了与随机数相同的数,*/
end=clock(); /*结束时钟*/
b=time(NULL); /*结束时间,时钟与时间解释见上*/
printf("\\1: It took you %6.3f seconds\\n",var=(double)(end-start)/18.2); /*显示花了多少时间,用的是时钟计算*/
printf("\\1: it took you %6.3f seconds\\n\\n",difftime(b,a)); /*显示花了多少时间,用的是时间计算*/
if(var<15) /*如果花费的时间(秒)小于15秒*/
printf("\\1\\1 You are very clever! \\1\\1\\n\\n"); /*提示你是高手*/
else if(var<25) /*在25秒内*/
printf("\\1\\1 you are normal! \\1\\1\\n\\n"); /*提示你是一般的家伙*/
else /*超过25秒*/
printf("\\1\\1 you are stupid! \\1\\1\\n\\n");/*提示你差的很*/
printf("\\1\\1 Congradulations \\1\\1\\n\\n"); /*提示恭喜*/
printf("The number you guess is %d",i); /*显示你猜的数*/
}
printf("\\ndo you want to try it again?(\\yy\\.or.\\n\\)\\n"); /*提示,还要继续吗?*/
if((c=getchar())=='y')/*输入y,则继续*/
goto loop; /*返回到开始猜数的地方*/
}


在本站查看更多关于用c语言编写猜数游戏,猜数游戏的教程    

没有任何图片教程
栏目导航
等级考试教程排行榜
  • 此栏目下没有热点教程
最近更新的教程