?? 在visual c++中怎樣獲取隨機(jī)數(shù).txt
字號(hào):
在Visual C++中怎樣獲取隨機(jī)數(shù)
編號(hào): QA000414
建立日期: 1999年1月26日 最后修改日期: 2003年1月4日
所屬類別: C/C++ - 其他方面
Microsoft Visual C++5.0
windows 98
請(qǐng)問(wèn),在Visual C++中怎樣獲取隨機(jī)數(shù)?不知如何獲取指定范圍內(nèi)的隨機(jī)數(shù)?(即實(shí)現(xiàn)Turbo C中random函數(shù)的功能)(李明洋)
使用rand函數(shù)獲得隨機(jī)數(shù)。rand函數(shù)返回的隨機(jī)數(shù)在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() );
}
在調(diào)用這個(gè)函數(shù)前,最好先調(diào)用srand函數(shù),如srand( (unsigned)time( NULL ) ),這樣可以每次產(chǎn)生的隨機(jī)數(shù)序列不同。詳見(jiàn)QA002136 "rand()每次產(chǎn)生的隨機(jī)數(shù)都一樣"。
如果要實(shí)現(xiàn)類似0-1之間的函數(shù),可以如下:
double randf()
{
return (double)(rand()/(double)RAND_MAX);
}
如果要實(shí)現(xiàn)類似Turbo C的random函數(shù),可以如下:
int random(int number)
{
return (int)(number/(float)RAND_MAX * rand());
}
?? 快捷鍵說(shuō)明
復(fù)制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號(hào)
Ctrl + =
減小字號(hào)
Ctrl + -