XC8, (45/18) not exactly 2.5?

Status
Not open for further replies.

sjb741

Junior Member level 2
Joined
Aug 6, 2021
Messages
20
Helped
0
Reputation
0
Reaction score
1
Trophy points
3
Activity points
222
//XC8 2.31

volatile uint32_t gRawCount;
//Watch result
gRawCount = (0.5 + (45/18)); //gRawCount = 2
gRawCount = (0.5 + 2.5); //gRawCount = 3

So (45/18) must have evaluated to a tiny bit under 2.5.
I am surprised becasue 0.5 is precisely representable as a floating point value (unlike say 0.1)
 

You are dividing integer numbers, the result is integer, too.

45/18 = 2

Learn about C type propagation and automatic type conversion.
 

    sjb741

    Points: 2
    Helpful Answer Positive Rating
Ah, that makes sense, thanks.

gRawCount = (0.5 + (45.0/18.0)); //gRawCount = 3
 

I don't know exactly which MCU you are using but generally try to avoid floating point numbers in XC8, only becasue the MCUs that it targets don't have any form of arithemtic unit - everything is done in firmware library functions that can take a lot of FLASH and can be (relatively) slow to execute.
Also remember that many compilers for embedded devices try not to automatically perform promotions which is why your original expression is completely performed in integer arithmetic (even if you were to delare the result as floating point).
You can often find ways to get around this using scaled integers and similar techniques.
Susan
 

Status
Not open for further replies.

Similar threads

Cookies are required to use this site. You must accept them to continue using the site. Learn more…