visual c++可变零校正
visual C++ Variable Zero Correction
变量"probability"总是显示为零,即使其他变量的输出与程序末尾的概率变量位于相同的放置区域。我有一种感觉,它与位置有关,但它可能是另一个初始化问题。概率永远不应该为零。
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <iomanip>
using namespace std;
int main() {
int die1,
die2,
sum,
turns,
win=0,
loss=0;
double probability=0;
int thepoint, rolls;
srand(time(0));
cout<<"How many turns would you like? ";
cin>>turns;
for(int i=0; i<turns; i++)
{
sum=0;
die1=rand()%6;
die2=rand()%6;
sum=die1+die2;
//cout<<"nFirst die is a "<<die1<<endl;
//cout<<"Second die is a "<<die2<<endl;
//cout<<"nn>>>Turn "<<i<<": You rolled "<<sum;
switch (sum){
case 2: case 3: case 12:
//cout<<"You have lost this turn with 2 3 or 12!"<<endl;
loss++;
break;
case 7:
//cout<<"nYea! You won this turn with a 7 on the first roll!"<<endl;
win++;
break;
case 11:
//cout<<"You won this turn ith 11!"<<endl;
win++;
break;
default:
//cout<<"nRolling again!"<<endl;
thepoint=sum;
rolls=1;
sum=0;
//cout<<"nRoll 1 - Your point is "<<thepoint<<endl;
while (sum != thepoint)
{
//srand(time(0));
die1=rand()%6;
die2=rand()%6;
sum=die1+die2;
rolls++;
//cout<<"Roll "<<rolls<<". You rolled "<<sum<<endl;
if (sum == thepoint)
{
//cout<<"You won this turn in the while with a point match!"<<endl;
win++;
break;
}
if (sum == 7)
{
loss++;
//cout<<"You lost this turn in the while with a 7"<<endl;
break;
}
}
}
}
probability = win/turns;
cout<<"No. of Turns: "<<turns<<"n";
cout<<"No. of Wins: "<<win<<"n";
cout<<"No. of Loses: "<<loss;
cout.precision(6);
cout<<"nExperimental probability of winning: "<<fixed<<probability;
cin.get();
cin.get();
return 0;
}
由于变量win
和turns
的数据类型为int
,并且probability
是实数(即这里的double),在执行除法之前,您需要将其中至少一个转换为double
。
probability = (double)win/turns;
顺便说一句,如果需要,但不是真的需要,也可以同时使用win
和turns
。
mod 6
操作% 6
将给您一个范围在0..5之间的数字(除以6后的余数)。您需要将1
添加到其中。
die1=rand()%6;
die2=rand()%6;
die1=1+rand()%6;
die2=1+rand()%6;
更新:虽然这是一个bug,但它不是导致概率打印为零的根本原因,真正的问题是由@Tuxdude指出的。
相关文章:
- Visual Studio 2015:Extern "C" 和 "export" 关键字
- 为cl.exe(Visual Studio代码)指定命令行C++版本
- 试图在visual studio上用C++创建一个桌面应用程序
- 如何在MS Visual Studio 2019中运行QT UI
- 如何使用Visual Studio 2017在C++中为参数化对象数组使用唯一指针
- Visual Studio Code - C++ Debugger 無法啟動
- Visual C++ constexpr Hints
- 为什么它不适用于Visual 2019的原因
- Visual Studio 2019:插入多个C++风格的单行注释
- Visual Studio Code "undefined reference to `WinMain@16'"
- visual在c++中将十进制数转换为二进制数
- Visual studio代码重构似乎不起作用(例如,重命名符号-f2)
- Visual Studio中的函数声明和函数定义问题
- 如何指定我希望我的LIB链接到的DLL文件?-Visual Studio 2019
- Visual C++(VS2017)中用户定义的转换不明确
- Visual C++GC接口如何启用它以及要包含哪个库
- visual是否可以在c++中创建一个接收无限数量相同类型(或至少相当数量)参数的函数
- visual c++,如何获取解决方案目录中的代码
- Visual Studio mkl_link_tool.exe链接错误
- Visual Studio(或任何其他工具)能否将地址解释为调用堆栈(boost上下文)的开头