My program seems to be ignoring my cents after the decimal point for total_charge. It adds the dollar amounts, but ignores or does not see the cents. Can anyone give me suggestions as to what I need to look at? I'm brand new at coding, thus the reason for all these questions. thanks!

Pete

#include <iostream>

using std::cout;
using std::cin;
using std::endl;
using std::ios;
using std::fixed;

#include <iomanip>

using std::setw;
using std::setiosflags;
using std::setprecision;

#include <cmath>


//function prototype
double calculateCharge(double);


int count;
int total_hours;
int total_charge;

int main()

{
    int num;
    int charge;

    int count = 1;   
    
    int total_hours = 0 ;
    
    int total_charge = 0 ;
 

    for( int i = 0; i < 3; ++i )


    {
        cout << "enter hours parked\n\n ";
        
        cin >> num ;

        charge = calculateCharge(num);

        cout<< setw(3)<< "CAR" << setw(26)<< "HOURS" << setw(27)<< "CHARGE\n";
        cout<< count << setw(25)<< num << setw(27)<< fixed << setprecision( 2 ) <<setw(24)<< "$"<< calculateCharge (num) << endl;
                
        count++;
        total_hours += num;
        total_charge += charge;
                
    }
        
        cout<< "\n\n" <<setw(23)<< "TOTAL = " <<total_hours <<setw(24)<< "$"<< setw(2)<< total_charge << endl;

        return 0;
}//end main



double calculateCharge( double x)
{

double charge;       

    if (x <= 3)
          charge = 2;
    
    else if (x >19)
           charge = 10;

    else if (x > 3)
            charge = 2 + (x - 3) * (.5);

return charge;

}

Recommended Answers

All 2 Replies

int charge;
int num

double calculateCharge(double);

charge = calculateCharge(num);

What you are doing here is trying to convert a double to an int. That's probably why you are loosing everything behind the decimal point (int's do not support decimal points).
Just declare everything as 'double' and voila!

1 other thing:

int count;
int total_hours;
int total_charge;

You declare these variables twice, once local and once global. Using global vars is never really a good idea, so you can just remove them, your program will run without them. (the globals are just above int main())

Ah, that makes sense, I guess I'll learn as I play around with it more. Thanks for your help, it's working now using double.

Pete

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.