0

即使其他变量的输出与程序结束时的概率变量位于同一放置区域,变量“概率”总是为零。我感觉它与放置有关,但这可能是另一个初始化问题。概率永远不应该为零。

#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<<"\n\n>>>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;
}
4

2 回答 2

5

由于变量winturns是数据类型int, 并且probability是实数(即此处为双精度数),因此您需要在double执行除法之前将其中至少一个转换为。

probability = (double)win/turns;

顺便说一句,如果需要但不是真的需要,同时投射win也没有害处。turns

于 2013-03-03T07:14:10.973 回答
3

mod 6操作% 6将为您提供 0..5 范围内的数字(除以 6 后的余数)。你需要补充1一点。

改变

die1=rand()%6;
die2=rand()%6;

die1=1+rand()%6;
die2=1+rand()%6;

更新:虽然这是一个错误,但它不是概率打印为零的根本原因,@Tuxdude 指出了真正的问题。

于 2013-03-03T07:15:49.307 回答