C++ 的新手。对于我们教授要求我们制作的这个骰子模拟器,我无法显示正确的格式 + 结果的百分比形式。我将在这里复制/粘贴她的说明,并希望得到有关如何纠正我在程序中百分比输出格式方面的错误的帮助。谢谢!
指示:
该程序应使用 C++ 随机数函数模拟单个骰子(骰子)(1-6) 的滚动。首先询问用户他们希望骰子(骰子)掷多少次。
接下来,让程序模拟用户请求的骰子(骰子)的滚动次数,并跟踪每次掷骰时骰子(骰子)落在哪个数字上。在程序结束时打印出一份报告,显示骰子(骰子)卷落在每个数字上的次数以及骰子(骰子)卷落在每个数字上的总次数的百分比。
不要在这方面使用函数或数组 - 使用我在讲座中向您展示的内容,您应该在讲座中始终聆听以获取正确的技巧,如果您忘记了我在讲座中所说的内容,请查看幻灯片。
输入验证:不允许用户输入小于 1 的数字作为他们想要掷骰子的次数。
输出应该如何(左侧)与我的输出(右侧):
#include <iostream>
#include <iomanip>
#include <string>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
srand((unsigned int)time(NULL));
int timesRolled;
int rolled;
float num1 = 0;
float num2 = 0;
float num3 = 0;
float num4 = 0;
float num5 = 0;
float num6 = 0;
cout << "How many times would you like to roll the dice?" << endl;
cin >> timesRolled;
for (int i = 0; i < timesRolled; i++)
{
rolled = rand() % 6 + 1;
if (rolled == 1)
{
num1++;
}
else if (rolled == 2)
{
num2++;
}
else if (rolled == 3)
{
num3++;
}
else if (rolled == 4)
{
num4++;
}
else if (rolled == 5)
{
num5++;
}
else if (rolled == 6)
{
num6++;
}
}
while (timesRolled < 1)
{
cout << "This is an invalid number. " << endl
<< "The number of rolls should be equal to or greater than 1." << endl
<< "Please enter again." << endl;
cin >> timesRolled;
}
cout << "\nDICE ROLL STATISTICS" << endl << endl
<< "# Rolled # Times % Times" << endl
<< "-------- -------- --------" << endl
<< setw(7) << "1" << setw(17) << fixed << setprecision(0) << num1 << setw(17) << fixed << setprecision(2) << (num1 / timesRolled) * 100 << "%" << endl
<< setw(7) << "2" << setw(17) << fixed << setprecision(0) << num2 << setw(17) << fixed << setprecision(2) << (num2 / timesRolled) * 100 << "%" << endl
<< setw(7) << "3" << setw(17) << fixed << setprecision(0) << num3 << setw(17) << fixed << setprecision(2) << (num3 / timesRolled) * 100 << "%" << endl
<< setw(7) << "4" << setw(17) << fixed << setprecision(0) << num4 << setw(17) << fixed << setprecision(2) << (num4 / timesRolled) * 100 << "%" << endl
<< setw(7) << "5" << setw(17) << fixed << setprecision(0) << num5 << setw(17) << fixed << setprecision(2) << (num5 / timesRolled) * 100 << "%" << endl
<< setw(7) << "6" << setw(17) << fixed << setprecision(0) << num6 << setw(17) << fixed << setprecision(2) << (num6 / timesRolled) * 100 << "%" << endl;
system("PAUSE");
return 0;
}
您可以看到我在哪里尝试使用 setprecision(在我的程序结束时)来操纵我最终百分比数字中的小数输出,但它似乎不起作用,这就是我需要帮助的地方。
您的问题是整数除法,例如:
(num1 / timesRolled) * 100 = 10 / 50 * 100 = 0 * 100 = 0;
请改用浮点值或在除法之前强制转换:
float num1 = 0;
或者
(static_cast<float>(num1) / timesRolled) * 100
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句