C ++ double to long

If I write code in C ++:

long long d = 999999998.9999999994; cout<<d; 

I get output: 999999999 (rounding)

But the output of this code is:

 long long d = 999999998.9999994994; cout<<d; 

- 999999998 (rounding)

It has something to do with accuracy. Is there any way to change the accuracy. The floor() function also gives the same result.

I also noticed that if I assign the value 8.9999994994 or 8.9999999994 d (above the variable). Output signal 8 .

+6
source share
2 answers

999999998.9999999994 not exactly representable in double , so the actual value is one of two representable numbers on either side of 999999998.9999999994 , either 999999998.99999988079071044921875 or 999999999 (if IEEE-754 binary64 format), selected in accordance with the implementation. Most systems will be rounded to the nearest by default, producing 999999999 .

The end result is that on those systems when you write 999999998.9999999994 , it gets the same effect as the record 999999999.0 . Therefore, the subsequent conversion gives 999999999 - the conversion from a floating point to an integer always truncates, but there is nothing to truncate here.

With 999999998.9999994994 nearest numbers represented are 999999998.999999523162841796875 and 999999998.99999940395355224609375 . Or one of them produces 999999998 after truncation. Similarly, with 8.9999999994 , the nearest numbers represented are 8.999999999399999950355777400545775890350341796875 and 8.9999999994000017267126168007962405681610107421875 , and after truncating one of them will produce 8 .

+10
source
 long long d = 999999998.9999999994; 

The closest value 999999998.9999999994 , which double can represent, is 999999999.0 - remember that floating points have finite precision;). Therefore, truncating decimal places gives 999999999 , and this is what is stored in d .

Using a literal with L -suffix really causes 999999998 stored in d - long double has higher precision.

 long long d = 999999998.9999994994; 

The closest 999999998.9999994994 value that double can represent is actually below 999999999 - about 999999998.999999523 on my machine. After this truncation of decimal places gives 999999998 and is stored in d .

+4
source

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


All Articles