码迷,mamicode.com
首页 > 其他好文 > 详细

鸡兔同笼随机数瞎蒙的实现 2014-08-26

时间:2015-05-14 20:12:44      阅读:99      评论:0      收藏:0      [点我收藏+]

标签:

今天C语小测验,这个思路还被老师批判了一番=.=


产生一个疑问:这个程序我循环10W次,如果在CMD里把每次循环的结果都显示出来,就得大约用半分钟的时间。如果我不printf每次的结果,大概3秒钟就能出最后的答案。


是CMD里的刷新速度有限制吗?有啥办法能既显示数据又能充分利用CPU的能力?


 

#include <stdio.h>
#include <time.h>
#include <stdlib.h>
//实验多少次
#define TIME 100000
//是否显示每次试验的数据
#define ECHO 0

void calculate_average(int*, int, int*);

int main()
{
    int rabbit, chick;
    int i; //每次试验蒙的次数
    int* count = malloc(sizeof(int)*TIME); //count指针
    int times = 0; //试验的总次数
    int* count_first = count; //记录count的最初地址

    srand((unsigned)time(NULL));

    while(1)
    {
        rabbit = rand()%36;
        chick = rand()%36;
        i++;

        if (35 == rabbit + chick && 94 == rabbit * 2 + chick * 4)
        {
                if (1 == ECHO)
                {
                    printf("%-4d次瞎蒙,得出兔子有%d个,鸡有%d枚,程序走了%d次\n",i,rabbit,chick,times);
                }

                *count = i; //把当前试验的次数保存到count
                count++;
                times++;
                i = 0;
                    while (TIME == times)
                    {
                        goto break_all; //跳出大循环
                    }
        }
    }
    break_all:

    calculate_average(count, times, count_first);

    return 0;
}

void calculate_average(int * count, int times, int* count_first)
{
    int sum = 0;
    int j;

    for (j = 0; j < times; j++)
    {
        sum += *count_first;
        count_first++;
    }
    printf("经过了%d试验,每次平均瞎蒙了%5d次\n",times,sum/times);
}


 

鸡兔同笼随机数瞎蒙的实现 2014-08-26

标签:

原文地址:http://www.cnblogs.com/wangyufeng22/p/4504008.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!