请教如何产生1-99的随机数

解决方案 »

  1.   

    #include <stdlib.h>
    #include <stdio.h>
    #include <time.h>void main( void )
    {
       int i;   /* Seed the random-number generator with current time so that
        * the numbers will be different every time we run.
        */
       srand( (unsigned)time( NULL ) );   /* Display 10 numbers. */
       for( i = 0;   i < 10;i++ )
          printf( "  %d\n", rand()%100 );
    }
      

  2.   

    /* RAND.C: This program seeds the random-number generator
     * with the time, then displays 10 random integers.
     */#include <stdlib.h>
    #include <stdio.h>
    #include <time.h>void main( void )
    {
       int i;   /* Seed the random-number generator with current time so that
        * the numbers will be different every time we run.
        */
       srand( (unsigned)time( NULL ) );   /* Display 10 numbers. */
       for( i = 0;   i < 10;i++ )
          printf( "  %6d\n", rand() );
    }
    Output    6929
        8026
       21987
       30734
       20587
        6699
       22034
       25051
        7988
       10104
      

  3.   

    ZT: http://www.luocong.com/articles/show_article.asp?Article_ID=24随机数的产生在病毒中占有十分重要的地位,尤其是在变形引擎中,没有它就不成事了……因此,今天就让我们来探讨一下如何产生一个随机数。首先值得说明的是,要产生一个随机数,方法有很多种,例如混沌和分形理论(原理比较复杂,但是公式却异常简单,将来有空的话我会介绍一下)……但是这些方法的缺点是计算难度大,需要花费的时间多,有没有一种实现起来比较简单的方法呢?答案是肯定的。我们先来看一条数学公式:Rand_Number = (Rand_Seed * X + Y) mod Z 利用这条公式,我们就可以生成一个伪随机数了。可是为什么是“伪随机数”呢?因为实际上要保证每次生成的随机数都不同,那是不太可能的,我们唯一能做到的只能是尽量使每次生成的数字与前面的不同,并且尽量使生成的数字均匀分布在指定的范围内。上面的这条公式就能满足这两点。至于为什么……呵呵,我也不懂,因为它牵涉到十分复杂的数学求证过程,我们只需要知道如何应用就成了:Rand_Seed 表示随机数种子,注意这个“种子”必须每次都不同,我们可以简单地利用 GetTickCount() 这个 API 来获得不同的数字,当然,你也可以用别的方法来取得,例如读取当前鼠标的坐标等等……X、Y必须至少有一个为素数。什么叫素数?Hoho,让我们来翻翻小学课本……素数就是除了 1 和它本身,不能被其他数整除的数字。在这里我们可以简单地给 X、Y 赋值 23 和 7 ,其实别的素数也行,我只是随便取了这两个数字。最后,Z 也应该是一个素数,这样才能保证产生的随机数能得到上限的值。不过我在实践中发现,这个 Z 不一定要准确地为素数。Why? I also don’t know...
      

  4.   

    我好佩服楼上  playfish()   这位,
    这么认真负责啊,
    让我学到好多东西,由衷的感谢