我的程序返回整数值,但即使在显式类型转换后也应该给出double值?

时间:2015-03-25 09:20:24

标签: c++

嘿伙计们我一直在遵循编程原则和实践使用C ++ - 2008,你知道谁(没有伤害意味着我能拼写它!!)我已经达到了第86页 并且有一个练习要求我们编写一个程序。这是我的版本。 这是main.cpp -

int main()
{
    int pennies,nickels,dimes,quarters,half_dollars;
    cout << "Enter the number of pennies,nickels,dimes,quarters<<endl<<"and  half dollars you have pls!!" << endl;
    cin>>pennies>>nickels>>dimes>>quarters>>half_dollars;
    no_of_each(pennies,nickels,dimes,quarters,half_dollars);
    total_money(pennies,nickels,dimes,quarters,half_dollars);

    return 0;
}

这是我制作的money.h头文件 -

void total_money(int pennies,int nickels,int dimes,int quarters,int half_dollars)
{
    int total_in_penny;
    double total_in_dollar;

    total_in_penny= (Penny*pennies)+ (Nickel*nickels)+ (Dime*dimes)+ (Quarter*quarters)+ (Halfdollar*half_dollars);

    total_in_dollar=(total_in_penny/100);

    cout<<"The total money in dollars is =$"<<(double)total_in_dollar<<endl
        <<"The total money in pennies is ="<<total_in_penny<<"cents"<<endl;
}

问题在于,当我尝试运行它(它成功建立)时,它显示了total_in_penny的良好结果,但没有显示total_in_dollar.I不知道为什么,因为我甚至尝试过显式类型转换在代码中。如果我错过了代码中的任何问题,请告诉我,我已经准备好听了。谢谢你的帮助! :)

2 个答案:

答案 0 :(得分:2)

除法的分子或分母必须是double才能获得double结果:

total_in_dollar=(double(total_in_penny)/100);

答案 1 :(得分:1)

请勿使用double来表示货币类型。有关详细信息,请参阅Why not use Double or Float to represent currency?

相反,试试这个:

int total_cents = 305;
int total_dollars = total_cents/100;
int fractional_dollars = total_cents%100;
std::cout << total_dollars << ".";
std::cout.width(2);
std::cout.fill('0');
std::cout << fractional_dollars << std::endl;

打印3.05