C++ floating point to integer type conversions

前端 未结 8 2252
长发绾君心
长发绾君心 2020-12-01 08:50

What are the different techniques used to convert float type of data to integer in C++?

#include 

using namespace std;
struct database {
  i         


        
8条回答
  •  执笔经年
    2020-12-01 09:35

    Size of some float types may exceed the size of int. This example shows a safe conversion of any float type to int using the int safeFloatToInt(const FloatType &num); function:

    #include 
    #include 
    using namespace std;
    
    template 
    int safeFloatToInt(const FloatType &num) {
       //check if float fits into integer
       if ( numeric_limits::digits < numeric_limits::digits) {
          // check if float is smaller than max int
          if( (num < static_cast( numeric_limits::max())) &&
              (num > static_cast( numeric_limits::min())) ) {
             return static_cast(num); //safe to cast
          } else {
            cerr << "Unsafe conversion of value:" << num << endl;
            //NaN is not defined for int return the largest int value
            return numeric_limits::max();
          }
       } else {
          //It is safe to cast
          return static_cast(num);
       }
    }
    int main(){
       double a=2251799813685240.0;
       float b=43.0;
       double c=23333.0;
       //unsafe cast
       cout << safeFloatToInt(a) << endl;
       cout << safeFloatToInt(b) << endl;
       cout << safeFloatToInt(c) << endl;
       return 0;
    }
    

    Result:

    Unsafe conversion of value:2.2518e+15
    2147483647
    43
    23333
    

提交回复
热议问题