zoukankan      html  css  js  c++  java
  • 鸡兔同笼随机数瞎蒙的实现 20140826

    今天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);
    }
    


  • 相关阅读:
    poj3181(Dollar Dayz)
    poj3666(Making the Grade)
    poj2392(Space Elevator)
    hdu5288(OO’s Sequence)
    hdu5289(Assignment)
    快学scala
    Spark Checkpointing
    Spark Performance Tuning (性能调优)
    Spark Memory Tuning (内存调优)
    Sparkstreaming and Kafka
  • 原文地址:https://www.cnblogs.com/wangyufeng22/p/4504008.html
Copyright © 2011-2022 走看看