zoukankan      html  css  js  c++  java
  • 猜数游戏中随机值设定的方式及优化

    最简单的猜数程序是这样的:

    用到了rand 函数,整体比较简单。

    #include<stdio.h>
    #include<stdlib.h>
    int main()
    {
       int magic;
       int guess;
       magic=rand();
       while(scanf("%d",&guess)==1)
       {
           if(guess==magic)
               printf("猜对辣! ");
           else if(guess>magic)
               printf("猜大辣 ");4
           else
            printf("猜小辣 ");
       }

        return 0;
    }
    这个程序的缺点就是,每次运行出的随机数都是同一个。如果用于游戏设计的话显然就很差劲,因此,第一步做了如下优化。

    #include<stdio.h>
    #include<stdlib.h>
    int main()
    {
       int magic;
       int guess;
       unsigned int seed;   //定义一个无符号整数
       scanf("%u",&seed);     //输入种子编号
       srand(seed);             //传入参数
       magic=rand();
       while(scanf("%d",&guess)==1)
       {
           if(guess==magic)
               printf("猜对辣! ");
           else if(guess>magic)
               printf("猜大辣 ");4
           else
            printf("猜小辣 ");
       }

        return 0;
    }
    运用了随机数种子,刚开始接触这个概念,还不是很会用。

    后来,觉得每次进行猜数之前要输入随机数种子,毕竟麻烦,因此又做了优化。

    采用时间函数,来调用计算机的时间来作为随机值。

    #include<stdio.h>
    #include<stdlib.h>
    #include<time.h>
    int main()
    {
       int magic;
       int guess;
       srand(time(NULL));             //传入参数
       magic=rand()%10;
       while(scanf("%d",&guess)==1)
       {
           if(guess==magic)
               printf("猜对辣! ");
           else if(guess>magic)
               printf("猜大辣 ");
           else
            printf("猜小辣 ");
       }

        return 0;
    }
    这样每次程序运行得出的随机值都不一样。

    该程序还可以加上计数等功能,这里就不展开说了。

  • 相关阅读:
    Min_25筛
    POJ-1068 Parencodings---模拟括号的配对
    POJ-3295 Tautology---栈+表达式求值
    POJ-2586 Y2K Accounting Bug贪心,区间盈利
    POJ-1328 Radar Installation--区间选点问题(贪心)
    POJ-2965 The Pilots Brothers' refrigerator---思维题
    POJ-1753 Flip Game---二进制枚举子集
    南阳OJ-2-括号配对问题---栈的应用
    hdu-1082 Matrix Chain Multiplication---栈的运用
    hdu-1237 简单计算器---中缀表达式转后缀表达式
  • 原文地址:https://www.cnblogs.com/hanlu-blog/p/6419945.html
Copyright © 2011-2022 走看看