Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Math With C++

Tags:

c++

math

I am a Java developer and I'm just starting to teach myself c++ as well. I know some of the differences between Java and c++ but I'm not sure what is going on here. Here is the code I am having a problem with. Its just from a tutorial so I'm not worried about accuracy.

void calculateHourly() {
    float totalWeeklyWage = mFltHourlySalary * mIntHoursWorked;
    float totalSales = mIntCostOfShoe * mIntUnitsSold;
    float totalCommission = (mIntHourlyCommission / 100) * totalSales;
    float grandTotalWage = totalWeeklyWage + totalCommission;

    cout << "You will get $" << grandTotalWage << " for selling " << mIntUnitsSold << " shoes in a week."
        << endl;
}

The problem is the line

float totalCommission = (mIntHourlyCommission / 100) * totalSales;

For whatever reason totalCommission = 0 when this method is done running. I have debugged this and all the other variables in this method equal what they are supposed to be equal to. With my Java cap on and the little knowledge I have of c++ tell me this should be working.

Am I missing something painfully simple in this method or is there a greater issue at hand? Any and all help is greatly appreciated.

like image 428
Jason Crosby Avatar asked Aug 06 '26 11:08

Jason Crosby


2 Answers

The 100 is being cast as an int and rounded.

You'll need to use

 float totalCommission = (mIntHourlyCommission / 100.) * totalSales;

or

 float totalCommission = (mIntHourlyCommission / (float) 100) * totalSales;

instead to directly cast it into the right type.

like image 95
count0 Avatar answered Aug 08 '26 01:08

count0


The following uses integer division, the result of which is also integer:

mIntHourlyCommission / 100

Either cast mIntHourlyCommission to float, or turn 100 into a float literal: 100.0f.

like image 41
NPE Avatar answered Aug 08 '26 02:08

NPE



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!