• Hello MLAers! We've re-enabled auto-approval for accounts. If you are still waiting on account approval, please check this thread for more information.

A simple C (Think C) question

PB170

6502
Just a simple C (Think C) question here. Can anyone explain why these two methods give different results? I have a decent understanding of how floating point numbers work in binary (5.67999…) and the problem with rounding during assignments, but I'm surprised that these two methods give different results. Could this be a Think C specific thing, or does it apply to C in general? (When I tried it with some online C compilers, both methods produce 568). Anyone who can enlighten me?

float float1 = 5.68;
float float2;
int integer;

Method 1:
integer = float1*100;
integer: 567

Method 2:
float2 = float1*100;
integer = float2;
integer: 568

 
Last edited by a moderator:
What machine are you compiling on, and what machine are you targeting? The presence of an FPU is very important, as the C standard leaves open the question of rounding. If this is software floating-point (i.e. not compiling for FPU), then I would not at all be surprised if there's just an inconsistency in how the floating-point lib handles rounding.

 
I'm using Think C 5.0 on a PowerBook 170 (with a 68882 FPU). I've never touched the compiler settings, but FPU instructions are turned off. Turning them on however doesn't affect the results.

 
I don’t know if this is the reason, but I believe that floating-point arithmetic is sometimes done at higher precision and then rounded. If you imagine a “two decimal digit” floating-point number, it would be like this:

decimal2 x = 2.9;
decimal2 y = 0.5;

integer i1 = x * y; // round 1.45 to 1
decimal2 f = x * y; // round 1.45 to 1.5
integer i2 = f; // round 1.5 to 2


You might be able to show this by looking at sizeof(float1) and sizeof(float1*100).

 
Back
Top