⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 在visual c++中怎样获取随机数.txt

📁 (1)满足均匀分布的[M,N]区间随机数
💻 TXT
字号:
 在Visual C++中怎样获取随机数 
编号: QA000414     
建立日期: 1999年1月26日 最后修改日期: 2003年1月4日 
所属类别: C/C++ - 其他方面
     
 
     Microsoft Visual C++5.0 
    windows 98 
    请问,在Visual C++中怎样获取随机数?不知如何获取指定范围内的随机数?(即实现Turbo C中random函数的功能)(李明洋)  
    
     使用rand函数获得随机数。rand函数返回的随机数在0-RAND_MAX(32767)之间。 
    例子: 
    /* 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() ); 
    } 
     
     
    在调用这个函数前,最好先调用srand函数,如srand( (unsigned)time( NULL ) ),这样可以每次产生的随机数序列不同。详见QA002136 "rand()每次产生的随机数都一样"。 
    如果要实现类似0-1之间的函数,可以如下: 
    double randf() 
    { 
     return (double)(rand()/(double)RAND_MAX); 
    } 
     
     
    如果要实现类似Turbo C的random函数,可以如下: 
    int random(int number) 
    { 
     return (int)(number/(float)RAND_MAX * rand()); 
    } 
     
      
 

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -