海淀团区委 文思君:怎么产生[1,100]的随机整数?

来源:百度文库 编辑:高校问答 时间:2024/04/29 05:17:47
C语言里的
rand()函数具体的怎么用呢?

听我讲解
rand()是产生一个正随机数
rand()%100就是0-99的随机数了,
所以rand()%100+1就可以了啊^-^

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

int 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() );

printf("\n");

// Usually, you will want to generate a number in a specific range,
// such as 1 to 100, like this:
{
int RANGE_MIN = 1;
int RANGE_MAX = 100;
for (i = 0; i < 10; i++ )
{
int rand100 = (((double) rand() /
(double) RAND_MAX) * RANGE_MAX + RANGE_MIN);
printf( " %6d\n", rand100);
}
}
}

对,下面的方法好多了,