C language loop structure and time function usage examples tutorial
- 2020-04-02 02:39:41
- OfStack
This paper illustrates the C language loop structure and the use of time function, which is a good reference for the learning of C language. Share with you for your reference. The details are as follows:
The complete example code is as follows:
#include <stdio.h>
#include <ctype.h>
#include <stdbool.h>
#include <time.h>
#include <stdlib.h>
int main(void)
{
char nextGame = 'Y';
bool correct = false;
int counter = 0;
int seq_len = 0;
int input_num = 0;
time_t seed = 0;
//int i = 0;
clock_t start_clock = 0;
int time_taken = 0;
printf("Here is a simon game for training memory ability .n");
printf("nThe screen will show a number sequence for 1 second , ");
printf("then the sequence will disappear. You are suggested to "
"input the same sequence to pass the game.n");
printf("nNotice this: each digit is seperated by a space. n");
printf("nNow press Enter to play .. Good luck !n");
scanf("%c",&nextGame); //Waiting for user's input
do
{
correct = true ;
counter = 0 ;
seq_len = 2 ;
time_taken = clock();
while(correct)
{
seq_len += (counter++ % 3 == 0);
//if "==" expression is true,returns 1; else returns 0
seed = time(NULL);
srand((unsigned int)seed);
//initialize the seed for rand() function
for(int i=0; i<seq_len; i++)
printf("%d ",rand() % 10);
//Output a random digit and a space
start_clock = clock() ;
//returns start clock time,clock() is a timer
for(;clock() - start_clock < CLOCKS_PER_SEC;) ;
//CLOCKS_PER_SEC is a const defined in time.h
printf("r");
//control char "r" : locator back to beginning of the line
for(int i=0; i<seq_len; i++)
printf(" ");
//two spaces to overwrite the sequence
printf("r");
srand((unsigned int)seed); //Restart the random sequence
for(int i=0; i<seq_len; i++)
{
scanf("%d",&input_num); //Read an input number
if(input_num != rand() % 10 )
{
correct = false ;
break;
}
}
printf("%sn",correct ? "Correct !" : "Wrong !");
}
time_taken=(clock() - time_taken) / CLOCKS_PER_SEC ;
printf("nnYour score is %d", --counter * 100 / time_taken);
fflush(stdin); //Empty the input buffer
printf("nDo you want to play again (y/n)? ");
scanf("%c",&nextGame);
} while(tolower(nextGame) == 'y');
return 0;
}
This example is from a foreign website, as a digital game, interested readers can debug the run, understand the code principle, deepen the understanding of C language loop domain time function.