I understand that nearbyint allows me to round integers without throwing exceptions. It is possible to use feclearexcept to check for errors or see if rounding took place (which will always be the case for nearbyint).
Can anyone show me an example of when an exception would have been thrown which has been avoided by using nearbyint?
Here is an example of the normal use of the function:
#include <cfenv>
#include <cmath>
#include <iostream>
void test(const char* title, int round_mode)
{
std::feclearexcept(FE_ALL_EXCEPT);
std::fesetround(round_mode);
std::cout << title << std::endl;
std::cout << "nearbyint(2.5) = " << std::nearbyint(2.5) << std::endl;
std::cout << "nearbyint(-2.5) = " << std::nearbyint(-2.5) << std::endl;
std::cout << "FE_INEXACT = " << std::boolalpha << (std::fetestexcept(FE_INEXACT) != 0) << std::endl << std::endl; // This will always be true.
}
#define test(mode) test(#mode, mode)
int main()
{
#ifdef FE_DOWNWARD
test(FE_DOWNWARD);
#endif
#ifdef FE_TONEAREST
test(FE_TONEAREST);
#endif
#ifdef FE_TOWARDZERO
test(FE_TOWARDZERO);
#endif
#ifdef FE_UPWARD
test(FE_UPWARD);
#endif
}
Aucun commentaire:
Enregistrer un commentaire