要是按单个数的概率怎么产生随机数?

解决方案 »

  1.   

    建立种子
    srand(a);
    产生随机数
     rand()
      

  2.   


    #include <iostream>
    #include <time.h>
    using namespace std;int main()
    {
    srand(unsigned(time(NULL)));
    int a[9];
    for(int i = 0 ; i < 9 ; i++)
    {
    if( i < 5)
    a[i] = rand() % 1 + 2 ;
    else 
    a[i] = rand() % 2;
    } for(i = 0 ; i < 9 ;i++ )
    cout<<a[i]<<' ' ; cout<<endl; return 0 ;
    }产生5个2
    这样写有局限性,主要是随机产生时设置一个rand()%?
    lz可以就此改进
      

  3.   

    Example/* 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() );
    }