1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
|
#include <iostream>
#include <cmath>
#include <limits>
int main()
{
constexpr long long ll_min = std::numeric_limits<long long>::min() ;
constexpr long long ll_max = std::numeric_limits<long long>::max() ;
std::cout << std::fixed << std::showpos << "rounding away from zero:\n" ;
for( double d : { -2.50, -2.49, -0.50, -0.49, 0.0, 0.49, 0.5, 2.49, 2.5,
-1.0e+20, 1.0e+20, /* out of range of integers */
-1.0e+30, 1.0e+30, /* huge value may not be exactly equal to integer -+ 10^30 */
-1.0/0.0, 1.0/0.0, 0.0/0.0 /* -+ infinity, nan */ } )
{
// see: https://en.cppreference.com/w/cpp/numeric/math/round
const double r = std::round(d) ;
std::cout << "number: " << d << " rounded: " << r << " (integer value is " ;
if( d >= ll_min && d <= ll_max ) std::cout << std::llround(d) ; // if d is within the range of long long
else std::cout << "out of range" ;
std::cout << ")\n" ;
}
}
|