Beginner
Beginner

Reputation: 233

Different answers: two simple identical integer calculations?

Below there are two scenarios where the operations are seemingly identical but produce results different by 1. I don't think I need to explain the programming, it's very simple.

The variable declarations are first, scenario 1 is 1) and 2 = 2), and the results obtained are listed last in each scenario.

Any help would be greatly appreciated.

int intWorkingNumber = 176555;

int intHundreds = 1;

int intPower = 1;

1)

int intDeductionValue = (intHundreds * 100 * pow(1000, intPower));

intWorkingNumber -= intDeductionValue;  

intWorkingNumber = 76555

2)

intWorkingNumber -= (intHundreds * 100 * pow(1000, intPower))

intWorkingNumber = 76554

Upvotes: 10

Views: 197

Answers (1)

Mark Byers
Mark Byers

Reputation: 837996

The difference between the two code samples is when you cast to int.

The first version is similar to this code, where you cast to integer before you subtract:

intWorkingNumber = 176555 - (int)(1 * 100 * pow(1000, 1));

The second version is similar to this, where you cast to integer after you subtract:

intWorkingNumber = (int)(176555 - (1 * 100 * pow(1000, 1)));

The function pow returns a floating point number. If the result of 1 * 100 * pow(1000, 1) is not exactly equal to 100000.0000 (and with floating point operations, you should not normally rely on exact results) these two are not equivalent.

Consider this simpler example:

x = 10 - (int)0.001;   // x = 10 - 0;     => x = 10
y = (int)(10 - 0.001); // y = (int)9.999; => y = 9

Upvotes: 17

Related Questions