C ++ Coin Toss Percentage

时间:2015-11-11 01:54:12

标签: c++

我正在编写一个程序,该程序应该请求用户想要翻转硬币的次数,然后计算被抛出的头部(头部为0,尾部为1)的百分比。但是,每次输出代码时,我的代码都会给我0%的头。 这是我的代码:

#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

double percentHeads(int userTosses) {
    srand(4444);
    int tossChance = (rand() % 1);
    int heads = 0;
    double percentCalc = static_cast<double>(heads) / userTosses * 100;  

    for (int i = 1; i <= userTosses; i++) {
        if (tossChance == 0) {
            heads++;
        }
    }
    return percentCalc;
}

int main() {
    int userTosses;
    int tossPercent;
    cout << "Enter the number of times you want to toss the coin: ";
    cin >> userTosses;
    cout << endl;

    tossPercent = percentHeads(userTosses);
    cout << "Heads came up " << tossPercent << "% of the time." << endl;

    return 0;
}

1 个答案:

答案 0 :(得分:3)

您正在错误的位置分配变量。此外,如果您尝试测试rand()是否返回奇数值,则需要使用一个(rand() & 1)进行按位AND。或者,如果您想查看它是否均匀,请使用2(rand() % 2)进行模数。

double percentHeads(int userTosses) {
    srand(4444);     // You should change this else you'll get same results
    int tossChance;
    int heads = 0;

    for (int i = 1; i <= userTosses; i++) {
        tossChance = rand() % 2;    // Move this here, and change to 2
        if (tossChance == 0) {
            heads++;
        }
    }
    // and move this here
    double percentCalc = static_cast<double>(heads) / userTosses * 100;  
    return percentCalc;
}