Std :: nearint vs std :: round in c ++ 11

C ++ 11 introduced std :: nearbyint and std :: round . Both return the "nearest" integer value.

When and where should I choose one after another?

I tested them with a value 0.5:

Case 1 : Demo for the closest connection

#include <iostream>
#include <cmath>

int main()
{
    std::cout<<"nearbyint(0.5) = "<<std::nearbyint(0.5);
}

conclusion: 0

Case 2: Demo for the Round

#include <iostream>
#include <cmath>

int main()
{
    std::cout<<"round(0.5) = "<<std::round(0.5);
}

conclusion: 1

Why different outputs?

+4
source share
2 answers

The function std::roundignores the current rounding mode , while taking std::nearbyintthis into account. You can change the rounding mode:

#include <cfenv>
int main() {
    std::fesetround(FE_UPWARD);
    // perform calculations
    std::fesetround(FE_DOWNWARD);
    // perform calculations
    // other rounding methods...
}

. std:: fegetround(). , ( ) 0, FE_TONEAREST.

+12

Ron answer, rint() nearbyint(), , round(), , , , . ISO ++ 2011 , 26.8 C library [c.math] C. ISO ISO 1999 round() :

7.12.9.6 [...] , , .

, round(), 4.3.1 IEEE 754 (2008) roundTiesToAway, , , FE_TONEAREST IEEE-754 (2008) roundTiesToEven, , . FE_TONEAREST, - , fesetround().

" " : 0.5 ( ) (1) round(), (0), nearbyint() rint().

+2

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


All Articles