C++硬币投掷百分比
C++ Coin Toss Percentage
我正在编写一个程序,该程序应该请求用户想要翻转硬币的次数,然后计算投掷的正面(正面为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;
}
相关文章:
- 最小硬币更换问题(自上而下方法)
- 编写一个函数以使用 n 百分比的 CPU 使用率
- 如何在硬币兑换问题中找到硬币的数量
- 获取 2 个数字之间的差异百分比
- 硬币兑换:找到多种方法来重现给定的总和
- 在 c++ 中模拟抛硬币时,模数如何工作?
- 在一定范围内生成随机数,其中一定百分比为特定值
- 用给定面值的最小硬币数量计价金额.贪婪的问题
- 抛硬币计数游戏C++数据结构!.
- 如何在硬币兑换中添加记忆
- 获得所需的最小射门次数,以便进球数超过射门数是给定的百分比
- 使用OpenCV计数硬币
- 如何计算单个元素在向量<float>中所有元素之和中的百分比
- 如何在AMD视频卡上获得GPU负载百分比和GPU温度
- 如何缩短此C++代码?(硬币兑换计算器)
- C++ 返回具有最小硬币的数组/向量以获得价值动态规划
- 位操纵:更难掷硬币
- 调试有偏差的硬币掷转 (C++)
- C++中的类/函数模板占用了我的二进制文件的百分比是多少?
- C++硬币投掷百分比