sandy2002 发表于 2005-7-29 15:40:00

rand()函数要怎样写

请问,如果我要写一个带参数的随机函数如: random(10) 则返回从0 - 10 之间的随机数,请问要怎样写呢,谢谢<br>

sandy2002 发表于 2005-7-29 18:08:00

是没人知道吗,还是各位大虾不屑指教?

ishou 发表于 2005-7-30 16:41:00

<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 &lt;stdlib.h&gt;
#include &lt;stdio.h&gt;
#include &lt;time.h&gt;

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 &lt; 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>

chxzhao 发表于 2005-7-31 12:08:00

<P>函数定义</P>
<P>int randBetween(int numL, int numH)<BR>{<BR>&nbsp;int a;<BR>&nbsp;double b;<BR>&nbsp;int c;</P>
<P>&nbsp;if (numL &gt; numH)&nbsp;//交换<BR>&nbsp;{<BR>&nbsp;&nbsp;int tmp;<BR>&nbsp;&nbsp;tmp = numH;<BR>&nbsp;&nbsp;numH = numL;<BR>&nbsp;&nbsp;numL = tmp;<BR>&nbsp;}</P>
<P>&nbsp;do <BR>&nbsp;{<BR>&nbsp;&nbsp;a = rand();&nbsp;&nbsp;//产生0到RAND_MAX之间的随机数<BR>&nbsp;&nbsp;b = a / sqrt(a + 1);<BR>&nbsp;&nbsp;c = (int)b;<BR>&nbsp;&nbsp;<BR>&nbsp;&nbsp;if (numL &lt;= c &amp;&amp; c &lt;= numH)<BR>&nbsp;&nbsp;{<BR>&nbsp;&nbsp;&nbsp;return c;<BR>&nbsp;&nbsp;}<BR>&nbsp;&nbsp;<BR>&nbsp;} while(1);<BR>}</P>
<P>函数调用</P>
<P>void Hello()</P>
<P>{</P>
<P>&nbsp;int nRan = randBetween(10, 20);<BR>&nbsp;ads_printf("\n 随机数= %d", nRan);</P>
<P>}</P>
页: [1]
查看完整版本: rand()函数要怎样写