Problem with float calculation

strange situation when executing the following lines of code:

const float a = 47.848711;
const float b = 47.862952;
float result = b - a;

I get the result (NSLog% .10f) = 0.0142440796.

I expected to get 0.0142410000.

What's happening?

+3
source share
2 answers

What if I ask you the following:

const int a = 1.3;
const int b = 2.7;
int result = b - a;

I get the result (NSLog% d) = 1.

I expected to get 1.4. What's happening?

In this case, the answer is obvious, right? 1.3 is not an integer, so the actual value that is stored in ais 1, and the value that is stored in bis not 2.7, but rather 2. When I subtract 1 from 2, I get exactly 1, which is the observed answer. If you're still with me, read on.


. 47.848711 float , a, :

a = 47.8487091064453125

, , b, 47.862952, :

b = 47.86295318603515625

, result, :

  47.86295318603515625
- 47.8487091064453125
----------------------
   0.01424407958984375

, , :

   0.0142440796
+3

!

( , , wikipedia).

+7

Source: https://habr.com/ru/post/1746503/


All Articles