68kMLA Classic Interface

This is a version of the 68kMLA forums for viewing on your favorite old mac. Visitors on modern platforms may prefer the main site.

Click here to select a new forum.
A simple C (Think C) question
Posted by: PB170 on 2021-01-28 10:52:22
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

Posted by: nkeck72 on 2021-01-28 11:01:37
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.

Posted by: PB170 on 2021-01-28 11:11:19
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.

Posted by: sfiera on 2021-01-30 02:39:26
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).

1