0

Hey guys I've been following Programming Principles and Practice Using C++ - 2008 by you know who(no harm meant I can't spell it!!) and I've reached page 86 and there is a exercise which asks us to write a program. This is my version of it. This is the 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;
}

And this is the money.h header file I made-

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;
}

The problem is that when I try to run it(it builds-up successfully),it shows good result for total_in_penny but not for the total_in_dollar.I don't know why, as I have even tried explicit type casting in the code. If there are any problems in the code I've missed please tell me I'm ready to hear it.Thanks guys for your help!! :)

niyasc
  • 4,440
  • 1
  • 23
  • 50
Avra Neel
  • 357
  • 1
  • 3
  • 7

2 Answers2

2

Either the numerator or the denominator of the division has to be a double to get a double result:

total_in_dollar=(double(total_in_penny)/100);
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
1

Please don't use double to represent monetary types. See Why not use Double or Float to represent currency? for more information.

Instead, try this:

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;

It prints 3.05.

Community
  • 1
  • 1
juhist
  • 4,210
  • 16
  • 33