首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

关于rand 函数生成随机数的疑点

2013-03-25 
关于rand 函数生成随机数的疑问//猜幻数游戏#include iostream#include cstdlibusing namespace stdi

关于rand 函数生成随机数的疑问
//猜幻数游戏
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
 
 
 int magic;
 int guess;
 magic=rand();
 cout<<"Guess the magic number.It is between 0 and 100."<<endl;
 for(int i=1;i<=5;i=i+1)
 {
  cin>>guess;
  if(guess==magic)
  {

  cout<<"***Right***"<<endl;
  break;
 }
 else
 {
  if(i==5)
   cout<<"The"<<i<<"time is wrong .End of game!"<<endl;
  else 
  {
   if(guess<magic)
    cout<<"You have been wrong for"<<i<<"time(s).Please try a bigger one."<<endl;
   else 
    cout<<"You have been wrong for"<<i<<"time(s).Please try smaller one."<<endl;
  }
 }
}
return 0;
} 为什么使用C++里生成随机数的函数rand   我的程序每次运行所产生的随机数都是一样的,不是应该随机生成的吗???求解释


[解决办法]
使用rand之前 加一个语句:srand(time(NULL))
[解决办法]

// 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 );
}

------解决方案--------------------


这是伪随机,,请重新设置种子
[解决办法]

引用:
C/C++ code?1234567891011121314151617181920212223242526272829303132333435363738394041// crt_rand.c// This program seeds the random-number generator// with the time, then exercises the rand……

拿走了
[解决办法]
一楼正解,把那个随便贴在rand函数之前就行了,别贴在循环体里面了。。。
[解决办法]
在循环体外面加入这么一句话srand((unsigned)time(NULL));
使用时间产生随机数种子就行了
[解决办法]
srand只需且必须在main开头第一句调用一次!
[解决办法]
在开始产生随机数之前加上一句srand((unsigned)time(NULL));就OK了。

热点排行