C语言循环结构与时间函数用法实例教程_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语言循环结构域时间函数的认识。

以上是小编为您精心准备的的内容,在的博客、问答、公众号、人物、课程等栏目也有的相关内容,欢迎继续使用右上角搜索按钮进行搜索c语言
, 函数
, 时间
, 用法
循环结构
c语言while循环的用法、c语言嵌套循环实例、c语言死循环代码实例、c语言 用法、c语言 的用法,以便于您获取更多的相关知识。

时间: 2024-08-22 15:18:21

C语言循环结构与时间函数用法实例教程_C 语言的相关文章

C语言变量类型与输出控制用法实例教程_C 语言

本文实例讲述了C语言变量类型与输出控制用法,有助于读者很好的对其进行总结与归纳.该实例分享给大家供大家参考借鉴之用.具体如下: 完整实例代码如下: /********************************************** **<Beginning C 4th Edition>Notes codes ** Created by Goopand ** Compiler: gcc 4.7.0 *******************************************

C语言中qsort函数用法实例小结_C 语言

本文实例汇总了C语言中qsort函数的常见用法,非常具有实用价值.分享给大家供大家参考.具体分析如下: C语言中的qsort函数包含在<stdlib.h>的头文件里,本文中排序都是采用的从小到大排序. 一.对int类型数组排序 int num[100]; int cmp ( const void *a , const void *b ) { return *(int *)a - *(int *)b; } qsort(num,100,sizeof(num[0]),cmp); 二.对char类型数

MFC之ComboBox控件用法实例教程_C 语言

本文以实例形式较为详细的讲述了MFC中ComboBox控件的用法.分享给大家供大家参考之用.具体方法如下: 一.ComboBox简介: ComboBox控件是由一个文本输入控件和一个下拉菜单组成的.用户可以从一个预先定义的列表里选择一个选项,同时也可以直接在文本框里面输入文本. 从工具栏中拖一个Combo Box控件.右击添加变量,变量名为cbBox. 二.用法: 1.为控件添加选项,指定默认选项 cbBox.AddString(_T("one")); cbBox.AddString(

C++类中的static和const用法实例教程_C 语言

static和const是C++程序设计中非常重要的概念,本文实例列举了C++类中的static和const的规则和用法.供大家参考借鉴.具体说明如下: 首先以代码用来举例说明.示例代码如下: class A { public: A():m(10) //const成员必须在构造函数的初始化构造列表中初始化 { q = 40; } void fun1()const { m++; //错误.const成员是常量,不能改变其值. n++; //正确.static变量n属于类,但是每个对象的函数都可以访

C语言中对于循环结构优化的一些入门级方法简介_C 语言

一.代码移动 将在循环里面多次计算,但是结果不会改变的计算,移到循环外面去. 例子: 优化前: void lower1(char *s){ int i; for(i=0;i<strlen(s);++i) if(s[i]>='A'&&s[i]<='Z') s[i]-=('A'-'a'); } 优化后: void lower2(char *s){ int i; int len=strlen(s); for(int i=0;i<len;++i) if(s[i]>='

C++中memset函数用法详解_C 语言

本文实例讲述了C++中memset函数用法.分享给大家供大家参考,具体如下: 功 能: 将s所指向的某一块内存中的每个字节的内容全部设置为ch指定的ASCII值,块的大小由第三个参数指定,这个函数通常为新申请的内存做初始化工作 用 法: void memset(void *s, char ch, unsigned n); 程序示例: #include <string.h> #include <stdio.h> #include <memory.h> int main(v

C++普通函数指针与成员函数指针实例解析_C 语言

C++的函数指针(function pointer)是通过指向函数的指针间接调用函数.相信很多人对指向一般函数的函数指针使用的比较多,而对指向类成员函数的函数指针则比较陌生.本文即对C++普通函数指针与成员函数指针进行实例解析. 一.普通函数指针 通常我们所说的函数指针指的是指向一般普通函数的指针.和其他指针一样,函数指针指向某种特定类型,所有被同一指针运用的函数必须具有相同的形参类型和返回类型. int (*pf)(int, int); // 声明函数指针 这里,pf指向的函数类型是int (

Python中zip()函数用法实例教程_python

本文实例讲述了Python中zip()函数的定义及用法,相信对于Python初学者有一定的借鉴价值.详情如下: 一.定义: zip([iterable, ...])zip()是Python的一个内建函数,它接受一系列可迭代的对象作为参数,将对象中对应的元素打包成一个个tuple(元组),然后返回由这些tuples组成的list(列表).若传入参数的长度不等,则返回list的长度和参数中长度最短的对象相同.利用*号操作符,可以将list unzip(解压). 二.用法示例: 读者看看下面的例子,对

详解C语言的结构体中成员变量偏移问题_C 语言

c语言中关于结构体的位置偏移原则简单,但经常忘记,做点笔记以是个记忆的好办法 原则有三个: a.结构体中的所有成员其首地址偏移量必须为器数据类型长度的整数被,其中第一个成员的首地址偏移量为0, 例如,若第二个成员类型为int,则其首地址偏移量必须为4的倍数,否则就要"首部填充":以此类推 b.结构体所占的总字节数即sizeof()函数返回的值必须是最大成员的长度的整数倍,否则要进行"末尾填充": c.若结构体A将结构体B作为其成员,则结构体B存储的首地址的偏移量必须