gpt4 book ai didi

C++ 抛硬币百分比

转载 作者:行者123 更新时间:2023-11-28 00:10:01 26 4
gpt4 key购买 nike

我正在编写一个程序,该程序应该请求用户想要抛硬币的次数,然后计算抛出的正面(正面为 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() 是否返回奇数,则需要对一个 (rand() & 1) 执行按位与操作。或者,如果您想查看它是否偶数,请对 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;
}

关于C++ 抛硬币百分比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33643002/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com