2013-03-03 61 views
0

即使其他變量的輸出與程序結束時的概率變量處於相同的放置區域,變量「概率」也始終爲零。我有一種感覺,它與放置有關,但它可能是另一個初始化問題。概率不應該爲零。C++變量零點校正

#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; 
} 
+2

'int/int = int' – chris 2013-03-03 07:12:54

回答

5

自變量winturns是數據類型int,而probability是實數(即雙倍這裏)你需要將它們中的至少一個轉換爲double你執行除法之前。

probability = (double)win/turns; 

BTW,有鑄造既win,太如果需要的話,但不是真的需要turns沒有壞處。

+0

雖然鑄造一個就足夠了。 – jrok 2013-03-03 07:16:50

+0

恕我直言雙(贏)更易讀 – Slava 2013-03-03 07:17:30

+0

是的,這是我在我的答案中提到,我可以更清楚地表明,如果這是不明確的。 – Tuxdude 2013-03-03 07:17:35

3

mod 6操作% 6會給你一個範圍爲0..5的數​​字(除以6後的餘數)。你需要添加1

變化

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

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

更新:雖然這是一個錯誤,它的概率不大打印零的根本原因,真正的問題是指出了@ Tuxdude。