软件注册站
热情软件屋

 
在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());
    
}
    
    

    
    相关书籍:
    《Visual C++常用数值算法集》

    

此问题由李海回答。

附加关键字:编程, 源程序, programming, source code, C/C++, MFC, C++ Builder, Borland C++, Turbo C, C, BCB, 其他方面,

   
 
把这个问题推荐给朋友
   
 
   
您的意见类别
您的名字
您的电子邮件
您的建议(请尽可能详细)
 
 

版权所有 1997-2008 热情软件屋
如果您有任何建议和意见, 请给我发个电子邮件 askpro@china-askpro.com
Web Designed by ZebraStudio