我在这段代码中正确实现了随机函数吗?

时间:2019-05-05 21:44:38

标签: c++

我正在编写一个使用rand(time(0))模拟抛硬币的程序。

我的作业说明:

  

编写一个程序,该程序在给定正面为double p(一次抛)的概率和实验次数为int n的情况下,模拟硬币的抛掷序列; (请参阅下面的说明)。

     

说明:

     

公平和不公平硬币:如果将公平硬币抛掷N次,则正面的相对频率(正面在N次抛掷中出现的次数除以实验次数N)接近正面的概率p = 1 N增加时为2。换句话说,在大约一半的抛掷中,头部抬起。如果正面(一次抛)的概率为p 6 = 1 2,则该硬币被称为不公平。

     

如何模拟抛硬币?假设给定了正面p 2(0; 1)的概率。假设bool y是一个包含模拟结果的变量;值true对应于正面,false对应于尾部。首先生成一个(均匀分布的)随机浮点​​数x 2 [0; 1]使用函数rand()。如果x < p,请设置y = true,否则请设置y = false。

     

说明:

     

实现功能bool coin_toss(double p),该功能以投入硬币的概率double p模拟硬币的抛掷。该函数的正面必须为true,反之则为false。要实现此功能,请遵循上述算法。

     

实施函数int head_frequency(double p, int n),该函数在给定正面为p2(0; 1)的情况下模拟n次抛硬币的序列。该函数必须返回n次抛出磁头的次数。要实现此功能,请使用函数coin_toss,它模拟硬币的一次抛掷。

     

编写一个程序,提示用户输入正面概率double p和实验次数int n。然后使用函数headfrequency模拟n次抛硬币的序列。该程序必须计算磁头的相对频率,并将其与概率p进行比较。

     

您可以假定用户输入始终有效。

     

实施一个循环,重复上述操作,直到用户请求退出为止。

     

使用srand(time(0))设置种子。请注意,您在计算机上获得的结果将不同于以下显示的输出,但是定性行为将是相同的。

我的代码如下:

#include <iostream>
#include <algorithm>
#include <string>
#include <cstdlib>
#include <cmath>
#include <iomanip>
#include <ctime>
using namespace std;

bool coin_toss(double p)
{
    srand(time(0));

    double random = 1 + rand() % 100;

    while (random > 1) { random = random / 10; };

    if (random < p) { return true; }

    else { return false; };

}

int head_frequency(double p, int n)
{
    int head = 0;

    for (int a = 1; a <= n; a++)
    {
        if (coin_toss(p)) { head = head + 1; };

    }


    return head;
}


int main()
{

    char counter;

    do {
        double prob;

        int times;

        cout << "Enter the probablity of heads 0 < p < 1: "; cin >> prob; cout << endl;

        cout << "Enter the number of experiments: "; cin >> times; cout << endl;

        double r_freq = head_frequency(prob, times) / times;

        cout << "\"Heads\" relative frequency: f = " << r_freq << endl;

        cout << "Distance : |f - p| = " << fabs(r_freq - prob) << endl;

        cout << "Would you like to continue? (y,n) "; cin >> counter;

    } while (counter == 'y');



    return 0;

}

我希望它能正确模拟随机。但是,无论我在程序中运行了多少次实验,我总是得到0个头,而且我找不到自己的错误。

0 个答案:

没有答案
相关问题