2017-03-29 7 views
-1
int main(){ 
    srand(time(0)); 
    int numOfTimes; 
    int randNum; 
    int oneRoll = 0, twoRoll = 0, threeRoll = 0, fourRoll = 0, fiveRoll = 0, sixRoll = 0; 
    int onePercent, twoPercent, threePercent, fourPercent, fivePercent, sixPercent; 

    int count = 0; 
    cout << "How many times would you like to roll the dice?\n"; 
    cin >> numOfTimes; 

    while (numOfTimes <= 0){ 
     cout << "Invalid entry enter a number greater than 0\n"; 
     cout << "How many times would you like to roll the dice?\n"; 
     cin >> numOfTimes; 
    } 

    while (count < numOfTimes) 
     { 
      randNum = rand() % 6 + 1; 

      switch (randNum) 
       { 
       case 1: 
        oneRoll++; 
        break; 
       case 2: 
        twoRoll++; 
        break; 
       case 3: 
        threeRoll++; 
        break; 
       case 4: 
        fourRoll++; 
        break; 
       case 5: 
        fiveRoll++; 
        break; 
       case 6: 
        sixRoll++; 
        break; 
       default: 
        cout << "\n"; 
       } 

      count++; 
     } 

    onePercent = (int)((oneRoll*100.0) /numOfTimes); 
    twoPercent = (int)((twoRoll*100.0)/numOfTimes); 

    cout << " # Rolled   # Times % Times" << endl; 
    cout << "--------- -------- --------" << endl; 
    cout << "1  " << oneRoll << "  " <<double (onePercent) << endl; 
    cout << "2  " << twoRoll << "  " << "" << endl; 
    cout << "3  " << threeRoll << "  " << ""<< endl; 
    cout << "4  " << fourRoll << "  " <<"" << endl; 
    cout << "5  " << fiveRoll << "  " <<"" << endl; 
    cout << "6  " << sixRoll << "  " <<"" << endl; 

1パーセントをダブルとして出力する必要があります。だから私はint型としてdouble型に変換したので、このような2つのゼロ(14.00)しか表示されませんが、唯一の変換では変換されません14C++は動作しないdouble型にキャストしよう

+0

doubleに変換するための正しい構文ではありませんか? – merlin2011

+0

[mcve]を含めてください。あなたは、単純な変換問題のために、たくさんのコードを歩き回ることは実際には期待できません。 –

+1

ダブルスを印刷したい場合は、変数を倍にします。 – tinstaafl

答えて

0

Barmarがコメントで述べたように、あなたは値が2進ポイントに印刷することにしたいが、あなたが行うとき、あなたはonePercentの数字を四捨五入:

onePercent = (int)((oneRoll*100.0) /numOfTimes); // Casting to "int" rounds off the number 

また、onePercentのための宣言されたデータ型は、最初からint次のとおりです。

int onePercent, twoPercent, threePercent, fourPercent, fivePercent, sixPercent; // onePercent is an "int" here 

あなたはintintをキャストしているので、だからあなたは、intの型キャストは必要ありません。

したがって、小数点以下2桁のonePercentを印刷しても、結果として常に.00が得られます。

(int)その式自体からキャストを取り除き、onePercentの初期データタイプをdoubleに変更することをお勧めします。 onePercentと一緒に宣言された他の変数のデータ型を変更しない場合は、onePercentを別の行にdoubleとして宣言します。こうすることで、計算後の値の精度が維持され、小数点以下2桁まで出力することができます。さておき、出力に小数点以下の桁数を指定するには、setprecision()機能を使用することができる

cout << setprecision(2) << ... << endl; // The value passed to "setprecision" is up to you. 
+0

ありがとうございました:) – george129

+0

@ george129私の答えがうまくいくなら、私の答えの隣にあるチェックマークを選択してください。あなたがそうするとき、私は緑になるはずです。ありがとう! –

関連する問題