#include <iostream>//C++标准输入输出函数
#include <cstdlib>//随机数等工具函数
#include <iomanip>//包含格式化数据流的流数据元
using namespace std;
int main()
{
for(int counter=1;counter<=100;counter++)
{
cout << setw(5) << (1+rand()%6) ;
if(counter%5 == 0)
cout << endl;
}
system("pause >> cout");
return 0;
}
//利用rand()获取随机数,而rand()%6再加1从而获取从1到6的随机数
//so nice
//投掷六面骰子6000000次
#include <iostream>
#include <cstdlib>
#include <iomanip>
using namespace std;
int main()
{
//记录1-6出现的频率,也就是在6000000次的掷骰子过程中出现的次数
int frequency1 = 0;
int frequency2 = 0;
int frequency3 = 0;
int frequency4 = 0;
int frequency5 = 0;
int frequency6 = 0;
int face ;//掷骰子过程中每一次骰子的点数
for(int counter=1;counter<=6000000;counter++)
{
face = 1 + rand()%6 ;//产生随机数
switch(face)
{
case 1:
frequency1 = frequency1 + 1;
break; //break不能忘啊,忘了就呵呵呵呵了,不信试试咯
case 2:
frequency2 = frequency2 + 1;
break;
case 3:
frequency3 = frequency3 + 1;
break;
case 4:
frequency4 = frequency4 + 1;
break;
case 5:
frequency5 = frequency5 + 1;
break;
case 6:
frequency6 = frequency6 + 1;
break;
default:
cout << "Program should never get here !" << endl;
}
}
cout << " Face" << setw(10) << "Frequency" << endl;
cout << " 1" << setw(10) << frequency1 << "\n"
<< " 2" << setw(10) << frequency2 << "\n"
<< " 3" << setw(10) << frequency3 << "\n"
<< " 4" << setw(10) << frequency4 << "\n"
<< " 5" << setw(10) << frequency5 << "\n"
<< " 6" << setw(10) << frequency6 << "\n"
<< endl;
system("pause >> cout ");
return 0;
}
//产生的随机数是重复的,该如何解决?
//调用<cstdlib>中的srand()函数,改变rand()函数的种子,(大概就是起点吧)
//为了保证产生的随机数不是全部一样的(运行多次程序)
//利用srand()函数确定每次产生随机数的起点,种子???
#include <iostream>
//using std::cin;
//using std::cout;
//using std::endl;
#include <iomanip>
//using std::setw;
#include <cstdlib>
//using std::rand;
//using std::srand;
using namespace std;
int main()
{
unsigned seed ;
cout << "enter seed :" ;
cin >> seed ;
srand(seed);
for(int counter=1;counter<=10;counter++)
{
cout << setw(5) << (1 + rand()%6) ;
if(counter%5 == 0)
cout << endl;
}
system("pause >> cout ");
return 0;
}
//但是输入相同的seed值,结果仍然是相同的啊!!!
本文使用C++编程语言实现了一个模拟六面骰子投掷的实验,通过随机数生成来模拟真实情况,并统计不同点数出现的频率,展示了随机数在概率实验中的应用。

被折叠的 条评论
为什么被折叠?



