c ++ cast int to double not working

时间:2017-03-29 23:43:42

标签: c++

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;

我需要它打印出百分之一作为双倍。所以我将它转换为int然后转换为double,因此它只打印两个这样的零(14.00),但它完全没有转换它只打印14

1 个答案:

答案 0 :(得分: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

因此,您不需要int的类型转换,因为您正在向int投射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.