用偏置硬币模拟抛硬币的程序

时间:2014-04-11 14:43:06

标签: c loops random

我没有任何代码,主要是因为我还没有开始处理这个特定的问题。这是我的C编程课的作业。

我的教授希望我们制作一个可以抛硬币(头或尾)10,000次的程序。但是,磁头元件有55%的可能性发生。我们必须使用具有用户提供的seed值的随机数生成器。

从概念上讲,我知道如何处理这个问题;编码方面,我不知道。我知道如何制作抛硬币计划,但没有偏见。

任何和所有帮助将不胜感激。

我附上了我的硬币计划程序的代码。我原本打算用这个作为这个新的偏见硬币抛掷计划的基础。

// CoinTosser_Homework4.cpp : Coin tossing program
// nxt3

#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#define HEADS 0
#define TAILS 1

int rand_int(int a, int b) {

return rand() % ((b - a + 1) + a);
}

int main() {

int tosses = 0, min = 0, heads = 0, tails = 0; //init tosses and number of user defined tosses

/*users input for number of tosses*/
printf("Enter number of coin tosses: ");
scanf("%i", &min);

while (tosses < min) {
    tosses++;
    if (rand_int(HEADS, TAILS) == HEADS)
        heads++;
    else
        tails++;
}

//prints results of tosses
printf("Number of heads: %i\n", heads);
printf("Number of tails: %i\n", tails);

return 0;
}

2 个答案:

答案 0 :(得分:2)

用老式的方式做到:

rand() % 100 + 1;

为您提供1到100(含)范围内的数字。如果该数字小于或等于55,那就是头。

但请注意,此生成器偏向,除非生成器的周期是100的倍数(可能不是)。 真正所做的是使用

之类的东西
(int)(100.0 * rand() / (RAND_MAX + 1.0)) + 1

100.0也绕过了整数除法。

答案 1 :(得分:1)

我忘记了C语法,但我可以为您提供C ++解决方案。从这里你可以看到算法。

#include <cstdlib>
#include <iostream>
#include <ctime>
using namespace std;

int main()
{
    int heads=0, tails=0;
    srand(time(NULL));
    number = rand() % 100 + 1;  //Generate random number 1 to 100
          if (number <= 55) //55% chance
                heads++; //This is head
          else
                tails++; //This is tail
}

说明:由于使用通常的随机数将为您提供正态分布而不是泊松数分布,您可以安全地使用条件if (number <= 55)生成概率为55%的概率

相关问题