源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

C++ 随机数与随机种子数的实例

  • 时间:2022-09-01 22:17 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:C++ 随机数与随机种子数的实例
[b]C++ 随机数与随机种子数的实例[/b] [b]实现效果图:[/b] [img]http://files.jb51.net/file_images/article/201707/201777110519697.png?20176711610[/img] 实例代码:
#include <stdlib.h> 
#include <iostream> 
#include <ctime> 
using namespace std; 
void Test() 
{ 
  int ran_num = 0; 
  cout<<"不指定seed,  "; 
  for(int i=0; i<10;i++) 
  { 
    ran_num = rand()%6; 
    cout<<ran_num<<" "; 
  }//每次运行都将输出:5,5,4,4,5,4,0,0,4,2 
 
  srand(1); 
  cout<<"\n指定seed为1, "; 
  for(int i=0; i<10;i++) 
  { 
    ran_num = rand()%6; 
    cout<<ran_num<<" "; 
  }//每次运行都将输出:5,5,4,4,5,4,0,0,4,2 
 
  srand(6); 
  cout<<"\n指定seed为6, "; 
  for(int i=0; i<10;i++) 
  { 
    ran_num = rand()%6; 
    cout<<ran_num<<" "; 
  }//每次运行都将输出:5,5,4,4,5,4,0,0,4,2 
  srand((unsigned)time(NULL)); 
  cout<<"\n指定seed当前系统时间, "; 
  for(int i=0; i<10;i++) 
  { 
    ran_num = rand()%6; 
    cout<<ran_num<<" "; 
  }//每次运行结果都不一样 
} 
/* 
1.随机数也随机种子数之间的关系:随机种子是用来打乱随机数的,没有它,你的随机数并不是真正随机 
2.种子与结果的关系是:对于不同的种子,有不同的随机数数列;对于相同的种子,具有相同的随机数数列 
3.一个项目中(可执行文件),就需要设置一次随机种子 
*/ 
int main() 
{ 
  Test(); 
  return 0; 
} 
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部