0

I'm learning about type conversion /type casting in C I have this code:

#include <stdio.h>
void main()
{
 float x=1.2;
 //Type conversion in c
 float conv=x+'a';
 printf("conv=%f",conv);
} 

I now 'a' is equal to int 97, and in the line x+'a' there is an implicit/compilator conversion so now i have x+97.000...(idk how many zeros)
But the output is:
conv=98.199997

So I have two questions, the first one is, why the result is not 98.2 exactly?
and my other question is, how can I generate exact arithmetic operations? I have to round the result? or which is the best way?

Sorry for my English.

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
Cblue X
  • 143
  • 6
  • 1
    "why the result is not 98.2" because `float` can only represent about 2^32 different values _exactly_. `1.2` and `98.2` are **not** in that set. – chux - Reinstate Monica Nov 16 '22 at 02:32
  • "how can i generate exact arithmetic operations?" Step 1, only use code values that are an integer times some power of 2, unlike 1.2 – chux - Reinstate Monica Nov 16 '22 at 02:33
  • You will get closer to your desired result using `double` instead of `float`. You are printing 8 decimal digits but `float` can really only support 6-7 decimal digits of accuracy. If you used `%.4f`, you'd probably get `98.2000` as desired. – Jonathan Leffler Nov 16 '22 at 03:29
  • Floats are 32 bits, and with 32 bits of information you can't represent an infinite set (|R). You can't have exact values for most real numbers, only for powers of 2 (including negative powers). – AR7CORE Nov 16 '22 at 06:41
  • 1
    @AR7CORE: That's a bit imprecise and may confuse folks who don't already understand. 21 is not a power of 2 but it can be stored exactly. – President James K. Polk Nov 16 '22 at 12:43
  • Absolutely, wrote a bit too fast, of course integers can be stored exactly. I meant sum of powers of 2 (including negative). Upvoted. – AR7CORE Nov 16 '22 at 12:50

0 Answers0