十味温胆汤 中成药:VC控制台程序如何使用rand()???

来源:百度文库 编辑:中科新闻网 时间:2024/04/28 03:20:39
我建立Win32控制台程序, 但是在里面就用不了随机函数rand(),不知道要加入什么头文件,我加入了 afx.h后,Compile是没错误了,但是Build的时候就出现三个错误.

要包含stdlib.h ,这个头文件:

你可以看看我的这个例子:

#include <stdlib.h>
#include <stdio.h>
#include <time.h>

void main( void )
{
int i;

srand( (unsigned)time( NULL ) );//这是一个种子,一定不要忘记!
for( i = 0; i < 10;i++ )
printf( " %6d\n", rand() );
}

Output //输出结果有可能不同

6929
8026
21987
30734
20587
6699
22034
25051
7988
10104

查MSDN,其中关于rand(),有这么一段描述:

Generates a pseudorandom number.
RoutineRequired Header
rand<stdlib.h>

int rand( void );
Libraries
All versions of the C run-time libraries.
Return Values
rand returns a pseudorandom number, as described above. There is no error return.
Remarks
The rand function returns a pseudorandom integer in the range 0 to RAND_MAX. Use the srand function to seed the pseudorandom-number generator before calling rand.
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() );
}
Output
6929
8026
21987
30734
20587
6699
22034
25051
7988
10104