Does casting to an int after std::floor guarantee the right result?

前端 未结 5 1488
旧巷少年郎
旧巷少年郎 2020-11-30 05:38

I\'d like a floor function with the syntax

int floor(double x);

but std::floor returns a double. Is<

5条回答
  •  时光取名叫无心
    2020-11-30 06:04

    If you want to deal with various numeric conditions and want to handle different types of conversions in a controlled way, then maybe you should look at the Boost.NumericConversion. This library allows to handle weird cases (like out-of-range, rounding, ranges, etc.)

    Here is the example from the documentation:

    #include 
    #include 
    
    int main() {
    
        typedef boost::numeric::converter Double2Int ;
    
        int x = Double2Int::convert(2.0);
        assert ( x == 2 );
    
        int y = Double2Int()(3.14); // As a function object.
        assert ( y == 3 ) ; // The default rounding is trunc.
    
        try
        {
            double m = boost::numeric::bounds::highest();
            int z = Double2Int::convert(m); // By default throws positive_overflow()
        }
        catch ( boost::numeric::positive_overflow const& )
        {
        }
    
        return 0;
    }
    

提交回复
热议问题