程序模拟带有偏向硬币的抛硬币 [英] Program that simulates a coin toss with a bias coin

查看:304
本文介绍了程序模拟带有偏向硬币的抛硬币的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I don't have any code, mainly because I haven't started working on this particular problem. It is for homework for my C Programming class.

我的教授希望我们创建一个程序,将一个硬币(正面或反面)抛掷10,000次.但是,heads元素有55%的机会发生.我们必须使用具有用户提供的seed值的随机数生成器.

My professor wants us to create a program that tosses a coin (heads or tails) 10,000 times. However, the heads element has a 55% chance to occur. We have to use a random number generator with a user-supplied seed value.

从概念上讲,我知道该如何处理;编码方面,我一无所知.我知道如何制作抛硬币程序,但是没有偏见.

Conceptually, I know how to approach this; coding-wise, I have no clue. I know how to make a coin tossing program, but not with a bias.

我们将不胜感激.

我已经为我的硬币投掷程序附加了代码.我原本打算以此为基础来创建这个新的 bias 投币程序.

I've attached code for my coin tosser program. I had intended to use this as a basis for this new bias coin tossing program.

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

推荐答案

以老式的方式进行操作:

Do it the old fashioned way:

rand() % 100 + 1;

为您提供1到100(含)范围内的数字.如果该数字小于或等于55,则为首.

gives you a number in the range 1 to 100 (inclusive). It's heads if that number is less than or equal to 55.

但是请注意,除非生成器的周期是100的倍数(可能不是)的倍数,否则此生成器是有偏差的.您应该真的要做的是使用类似

But note that this generator is biased unless the periodicity of the generator is a multiple of 100 (which is probably isn't). What you should really do is use something like

(int)(100.0 * rand() / (RAND_MAX + 1.0)) + 1

100.0还规避了整数除法.

这篇关于程序模拟带有偏向硬币的抛硬币的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆