请各位给写个随机函数的语句!该如何解决
请各位给写个随机函数的语句!!
比如说我要随机把id取出,怎么编随机函数??用数组,设一个变量等等
------解决方案--------------------
srand(),rand()
// crt_rand.c
// This program seeds the random-number generator
// with the time, then exercises the rand function.
//
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
void SimpleRandDemo( int n )
{
// Print n random numbers.
int i;
for( i = 0; i < n; i++ )
printf( " %6d\n", rand() );
}
void RangedRandDemo( int range_min, int range_max, int n )
{
// Generate random numbers in the half-closed interval
// [range_min, range_max). In other words,
// range_min <= random number < range_max
int i;
for ( i = 0; i < n; i++ )
{
int u = (double)rand() / (RAND_MAX + 1) * (range_max - range_min)
+ range_min;
printf( " %6d\n", u);
}
}
int main( void )
{
// Seed the random-number generator with the current time so that
// the numbers will be different every time we run.
srand( (unsigned)time( NULL ) );
SimpleRandDemo( 10 );
printf("\n");
RangedRandDemo( -100, 100, 10 );
}
------解决方案--------------------
我写过一个简单的
void CFileTransferDll::getCid()
{
int i, j;
char c[10];
memset(c, 0, 10);
srand((int)time(0));
for(i = 0; i < 9; i++)
{
j = ((int)(rand()))%(10);
sprintf(&(c[i]), "%d", j);
}
if(c[0] == '0')
c[0] = '1';
m_pCid = c;
}
------解决方案--------------------
RAND产生随机数的机制与执行的时刻(时间点)有关,直接使用RAND你会发现怪异的现象,可能每次所产生的一系列“随机数”出奇的一致,属于伪随机数。
产生真正的随机数是实现一个复杂算法的问题。
不过也有简单可将就用的方法
比如说我要随机把id取出,怎么编随机函数??用数组,设一个变量等等
------解决方案--------------------
srand(),rand()
// crt_rand.c
// This program seeds the random-number generator
// with the time, then exercises the rand function.
//
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
void SimpleRandDemo( int n )
{
// Print n random numbers.
int i;
for( i = 0; i < n; i++ )
printf( " %6d\n", rand() );
}
void RangedRandDemo( int range_min, int range_max, int n )
{
// Generate random numbers in the half-closed interval
// [range_min, range_max). In other words,
// range_min <= random number < range_max
int i;
for ( i = 0; i < n; i++ )
{
int u = (double)rand() / (RAND_MAX + 1) * (range_max - range_min)
+ range_min;
printf( " %6d\n", u);
}
}
int main( void )
{
// Seed the random-number generator with the current time so that
// the numbers will be different every time we run.
srand( (unsigned)time( NULL ) );
SimpleRandDemo( 10 );
printf("\n");
RangedRandDemo( -100, 100, 10 );
}
------解决方案--------------------
我写过一个简单的
void CFileTransferDll::getCid()
{
int i, j;
char c[10];
memset(c, 0, 10);
srand((int)time(0));
for(i = 0; i < 9; i++)
{
j = ((int)(rand()))%(10);
sprintf(&(c[i]), "%d", j);
}
if(c[0] == '0')
c[0] = '1';
m_pCid = c;
}
------解决方案--------------------
RAND产生随机数的机制与执行的时刻(时间点)有关,直接使用RAND你会发现怪异的现象,可能每次所产生的一系列“随机数”出奇的一致,属于伪随机数。
产生真正的随机数是实现一个复杂算法的问题。
不过也有简单可将就用的方法
- C/C++ code
int iRand; srand((unsigned)time(0)); iRand = rand() % MAX_VAL; // MAX_VAL是需要你定义的随机数范围最大值,即你想取的随机数范围为[0, MAX_VAL)