C++硬币投掷百分比

C++ Coin Toss Percentage

本文关键字:百分比 硬币 C++      更新时间:2023-10-16

我正在编写一个程序,该程序应该请求用户想要翻转硬币的次数,然后计算投掷的正面(正面为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;
}

您将变量分配到了错误的位置。此外,如果您试图测试rand()是否返回奇数,则需要对1(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;
}