C语言循环结构与时间函数用法实例教程
本文实例展示了C语言循环结构与时间函数用法,对于C语言的学习来说是非常不错的参考借鉴材料。分享给大家供大家参考之用。具体如下:
完整实例代码如下:
/**********************************************
**《BeginningC4thEdition》Notescodes
**CreatedbyGoopand
**Compiler:gcc4.7.0
***********************************************/
/*Simongames:memoryabilitytest*/
#include<stdio.h>/*forprintf(),scanf()function*/
#include<ctype.h>/*fortolower()function*/
#include<stdbool.h>/*forbooltype:true,false*/
#include<time.h>/*fortime()function*/
#include<stdlib.h>/*forrand(),srand()function*/
intmain(void)
{
charnextGame='Y';/*goaheadforanothergame*/
boolcorrect=false;/*guesscorrectly*/
intcounter=0;/*numberofsequencesguessedcorrectly*/
intseq_len=0;/*lengthofsequence*/
intinput_num=0;/*storesaninputdigit*/
time_tseed=0;/*seedvalueforrandomnumbersequence*/
//inti=0;/*forloopvariable*/
clock_tstart_clock=0;/*recordstartclocktime(notsecond)*/
inttime_taken=0;/*Timeusedforgameinseconds*/
printf("Hereisasimongamefortrainingmemoryability.\n");
printf("\nThescreenwillshowanumbersequencefor1second,");
printf("thenthesequencewilldisappear.Youaresuggestedto"
"inputthesamesequencetopassthegame.\n");
printf("\nNoticethis:eachdigitisseperatedbyaspace.\n");
printf("\nNowpressEntertoplay..Goodluck!\n");
scanf("%c",&nextGame);//Waitingforuser'sinput
do
{
correct=true;
counter=0;/*successfultries*/
seq_len=2;/*Initiallengthofadigitsequence*/
time_taken=clock();
while(correct)
{
/*Oneachthirdsuccessfultry,increasethesquencelength*/
seq_len+=(counter++%3==0);
//if"=="expressionistrue,returns1;elsereturns0
/*time(NULL)returnsnumberofsecondssince1970-01-01*/
seed=time(NULL);
/*Generateanddisplayasequenceofrandomnumbers*/
srand((unsignedint)seed);
//initializetheseedforrand()function
for(inti=0;i<seq_len;i++)
printf("%d",rand()%10);
//Outputarandomdigitandaspace
/*Waitonesecond*/
start_clock=clock();
//returnsstartclocktime,clock()isatimer
for(;clock()-start_clock<CLOCKS_PER_SEC;);
//CLOCKS_PER_SECisaconstdefinedintime.h
/*Nowoverwritethedigitsequence*/
printf("\r");
//controlchar"\r":locatorbacktobeginningoftheline
for(inti=0;i<seq_len;i++)
printf("");
//twospacestooverwritethesequence
printf("\r");
/*Checkwethertheinputsequenceiscorrect*/
srand((unsignedint)seed);//Restarttherandomsequence
for(inti=0;i<seq_len;i++)
{
scanf("%d",&input_num);//Readaninputnumber
if(input_num!=rand()%10)
{
correct=false;
break;
}
}
printf("%s\n",correct?"Correct!":"Wrong!");
}
/*Calculatetotaltimetoplaythegameinseconds*/
time_taken=(clock()-time_taken)/CLOCKS_PER_SEC;
/*Outputthetotalgamescore*/
printf("\n\nYourscoreis%d",--counter*100/time_taken);
fflush(stdin);//Emptytheinputbuffer
printf("\nDoyouwanttoplayagain(y/n)?");
scanf("%c",&nextGame);
}while(tolower(nextGame)=='y');
return0;
}
本文实例源自国外网站,为一个数字游戏,感兴趣的读者可以调试运行一下,体会代码的原理,加深对C语言循环结构域时间函数的认识。