简体   繁体   中英

Using Math With C++

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.

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.

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 .

你的mIntHourlyCommission int是否小于100?

In general you should never ever use floats for money. Use the largest int-type available for the smallest amount you are dealing with (eg long int for cent).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM