rand()函数要怎样写
请问,如果我要写一个带参数的随机函数如: random(10) 则返回从0 - 10 之间的随机数,请问要怎样写呢,谢谢<br> 是没人知道吗,还是各位大虾不屑指教? <P class=t>The rand function returns a pseudorandom integer in the range 0 to RAND_MAX. Use the <A class=normal href="mk:@ivt:vccore/F3F/F43/D4D/S4CF68.HTM" target="_blank" >srand</A> function to seed the pseudorandom-number generator before calling rand.</P><P class=rl>Example</P>
<P class=spacing><BR></P><PRE>/* 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() );
}
</PRE>
<P class=rl>Output</P>
<P class=spacing><BR></P><PRE>6929
8026
21987
30734
20587
6699
22034
25051
7988
10104
</PRE> <P>函数定义</P>
<P>int randBetween(int numL, int numH)<BR>{<BR> int a;<BR> double b;<BR> int c;</P>
<P> if (numL > numH) //交换<BR> {<BR> int tmp;<BR> tmp = numH;<BR> numH = numL;<BR> numL = tmp;<BR> }</P>
<P> do <BR> {<BR> a = rand(); //产生0到RAND_MAX之间的随机数<BR> b = a / sqrt(a + 1);<BR> c = (int)b;<BR> <BR> if (numL <= c && c <= numH)<BR> {<BR> return c;<BR> }<BR> <BR> } while(1);<BR>}</P>
<P>函数调用</P>
<P>void Hello()</P>
<P>{</P>
<P> int nRan = randBetween(10, 20);<BR> ads_printf("\n 随机数= %d", nRan);</P>
<P>}</P>
页:
[1]