C语言循环结构与时间函数用法实例教程

本文实例展示了C语言循环结构与时间函数用法,对于C语言的学习来说是非常不错的参考借鉴材料。分享给大家供大家参考之用。具体如下:

完整实例代码如下:

/**********************************************
** 《Beginning C 4th Edition》 Notes codes
** Created by Goopand
** Compiler: gcc 4.7.0
***********************************************/
/* Simon games : memory ability test */
#include <stdio.h>       /* for printf(),scanf() function */
#include <ctype.h>       /* for tolower() function */
#include <stdbool.h>      /* for bool type: true, false */
#include <time.h>        /* for time() function */
#include <stdlib.h>       /* for rand(),srand() function */

int main(void)
{
    char nextGame = 'Y';      /* go ahead for another game */
    bool correct = false;      /* guess correctly */
    int counter = 0;        /* number of sequences guessed correctly */
    int seq_len = 0;        /* length of sequence */
    int input_num = 0;       /* stores an input digit */
    time_t seed = 0;        /* seed value for random number sequence */
    //int i = 0;            /* for loop variable */

    clock_t start_clock = 0;    /* record start clock time (not second) */
    int time_taken = 0;       /* Time used for game in seconds */

    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 ;  /* successful tries */
        seq_len = 2 ;  /* Initial length of a digit sequence */
        time_taken = clock();

        while(correct)
        {
            /* On each third successful try, increase the squence length */
            seq_len += (counter++ % 3 == 0);
            //if "==" expression is true,returns 1; else returns 0

            /* time(NULL) returns number of seconds since 1970-01-01 */
            seed = time(NULL);

            /* Generate and display a sequence of random numbers */
            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

            /* Wait one second */
            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

            /* Now overwrite the digit sequence */
            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");

            /* Check wether the input sequence is correct */
            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("%s\n",correct ? "Correct !" : "Wrong !");
        }

        /* Calculate total time to play the game in seconds */
        time_taken=(clock() - time_taken) / CLOCKS_PER_SEC ;

        /* Output the total game score */
        printf("\n\nYour 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;
}

本文实例源自国外网站,为一个数字游戏,感兴趣的读者可以调试运行一下,体会代码的原理,加深对C语言循环结构域时间函数的认识。

(0)

相关推荐

  • c语言实现系统时间校正工具代码分享

    复制代码 代码如下: //*******************************************************************//Time Protocol是一种非常简单的应用层协议.它返回一个未格式化的32位二进制数字, //这个数字描述了从1900年1月1日午夜到现在的秒数.服务器在端口37监听协议请求,以 //TCP/IP或者UDP/IP格式返回响应.将服务器的返回值转化为本地时间是客户端程序的责任. //这里使用的时间服务器是129.132.2.21,更

  • c语言strftime时间格式化示例

    函数原型: 复制代码 代码如下: size_t strftime (char* ptr, size_t maxsize, const char* format,const struct tm* timeptr ); 代码示例: 复制代码 代码如下: #include <stdio.h>#include <time.h> int main (){    time_t rawtime;    struct tm * timeinfo;    char buffer [128]; tim

  • C语言中读取时间日期的基本方法

    C语言time()函数:获取当前时间(以秒数表示) 头文件: #include <time.h> 定义函数: time_t time(time_t *t); 函数说明:此函数会返回从公元 1970 年1 月1 日的UTC 时间从0 时0 分0 秒算起到现在所经过的秒数.如果t 并非空指针的话,此函数也会将返回值存到t 指针所指的内存. 返回值:成功则返回秒数,失败则返回((time_t)-1)值,错误原因存于errno 中. 范例 #include <time.h> main(){

  • 使用C语言中的time函数获取系统时间

    可以通过time()函数来获得计算机系统当前的日历时间(Calendar Time),处理日期时间的函数都是以本函数的返回值为基础进行运算.其原型为:time_t time(time_t * t);如果你已经声明了参数t,你可以从参数t返回现在的日历时间,同时也可以通过返回值返回现在的日历时间,即从一个时间点(例如:1970年1月1日0时0分0秒)到现在此时的秒数.如果参数为空(NULL),函数将只通过返回值返回现在的日历时间,比如下面这个例子用来显示当前的日历时间: 复制代码 代码如下: #i

  • 在C语言中转换时间的基本方法介绍

    C语言mktime()函数:将时间转换成经过的秒数 头文件: #include <time.h> 定义函数: time_t mktime(strcut tm * timeptr); 函数说明:mktime()用来将参数timeptr 所指的tm 结构数据转换成从公元1970 年1 月1 日0 时0 分0 秒算起至今的UTC 时间所经过的秒数. 返回值:返回经过的秒数. 范例:用time()取得时间 (秒数), 利用localtime() 转换成struct tm 再利用mktine()将str

  • C语言中用于修改文件的存取时间的函数使用

    C语言utime()函数:修改文件的存取时间和更改时间 头文件: #include <sys/types.h> #include <utime.h> 定义函数: int utime(const char * filename, struct utimbuf * buf); 函数说明:utime()用来修改参数filename 文件所属的inode 存取时间.结构utimbuf 定义如下: struct utimbuf { time_t actime; time_t modtime;

  • 浅谈时间戳与日期时间互转C语言

    浅谈时间戳与日期时间互转C语言 /* * ctime.h * * Created on: May 19, 2016 * */ #ifndef CTIME_H_ #define CTIME_H_ #include "common/micro_type.h" #define OFFSET_SECOND 946684800 /* ��1970/1/1/0/0/0��2000/1/1/0/0/0֮��������� */ //#define OFFSET_SECOND 0 /* ��2000/

  • C语言实现时间戳转日期的算法(推荐)

    1.算法 时间是有周期规律的,4年一个周期(平年.平年.平年.闰年)共计1461天.Windows上C库函数time(NULL)返回的是从1970年1月1日以来的毫秒数,我们最后算出来的年数一定要加上这个基数1970.总的天数除以1461就可以知道经历了多少个周期:总的天数对1461取余数就可以知道剩余的不足一个周期的天数,对这个余数进行判断也就可以得到月份和日了. 当然了,C语言库函数:localtime就可以获得一个时间戳对应的具体日期了,这里 主要说的是实现的一种算法. 2.C语言代码实现

  • C语言中将日期和时间以字符串格式输出的方法

    ctime()函数: 头文件: #include <time.h> 定义函数: char *ctime(const time_t *timep); 函数说明:ctime()将参数timep 所指的time_t 结构中的信息转换成真实世界所使用的时间日期表示方法,然后将结果以字符串形态返回.此函数已经由时区转换成当地时间,字符串格式为"Wed Jun 30 21 :49 :08 1993\n". 注意:若再调用相关的时间日期函数,此字符串可能会被破坏. 返回值:返回一字符串表

  • C语言中时间的基本用法小结

    前言 在我学的这些编程语言中,总是记不住它们的时间处理方式,每次用到时都要重新看,所以想着在这里记录下来,也方便用到时查找,也方便有需要的朋友们参考. time_t和struct tm 在C语言中用time_t类型表示一个时间,通常它是一个和long一样长的整数,也就是说,在32位环境下,它是4字节,在64位环境下,它是8字节.它保存的就是一个整数值,表示了从1970-01-01 08:00:00到其所表示时间的秒数,它是一个非负整数,所以,time_t无法表示早于1970-01-01 08:0

随机推荐