Is it safe to distinguish int from std :: round?

I have a question about std :: round with a signature:double round (double x);

Let's say I have this code:

int i = std::round(0.9);

In this case, I std::roundshould return 1.00000000000, but this is inconveniently close to 0.9999999999999, and I am worried that the floating point errors end in rounding.

I hope so i == 1, but is it guaranteed?

+4
source share
5 answers

The function std::roundreturns a floating point value, "rounding half the cases from zero." As with any implicit conversion doubleto int, the compiler will generate a warning:

conversion from 'double' to 'int', possible data loss

std:: lround std:: lrint, .

+6

. .

: std::round(0.9) 1.0 i == 1

, double.

, IEEE754 double 52- 2 ! , , no-op. , , , std::round(4503599627370496.5) 4503599627370496, , 4503599627370496.5 double .

, std::round , - , a.5 ( ) , ​​ . , 0.5 , , , -.

+6

++ C. N1570 (~ C11) round :

round , , .

, , , lrint, , .

+5

cppreference:

prvalue . , .. . , undefined ( type is unsigned, ). - bool, (. ).

+1

0.5, int ()

if(x < 0) { //number is negative
 return (int) x - 0.5;
} else {
 return (int) x + 0.5;//number is positive
}

1 1.49999999999, int, 1

-1

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


All Articles