2010-03-30 103 views
19

在C++中用于将浮点型数据转换为整型的不同技术有哪些?C++浮点型到整数型转换

#include<iostream> 
using namespace std; 
struct database 
{ 
    int id,age; 
    float salary; 
}; 
int main() 
{ 
    struct database employee; 
    employee.id=1; 
    employee.age=23; 
    employee.salary=45678.90; 
    /* 
    How can i print this value as an integer 
    (with out changing the salary data type in the declaration part) ? 
    */ 
    cout<<endl<<employee.id<<endl<<employee.age<<endl<<employee.salary<<endl; 
    return 0; 
} 
+1

HTTP://www.cs.tut。fi /〜jkorpela/round.html – 2010-03-30 10:27:18

回答

26

普通的方法是:

float f = 3.4; 
int n = static_cast<int>(f); 
+8

有关结果的其他信息将会有所帮助。 – ManuelSchneid3r 2016-10-30 07:48:50

25

你所寻找的是 '类型转换'。类型转换(把你需要的类型知道括号)告诉编译器你知道你在做什么,并且很酷。从C继承的旧方式如下。

float var_a = 9.99; 
int var_b = (int)var_a; 

如果你只有试着写

int var_b = var_a; 

你会得到你不能隐式(自动)转换floatint,因为你失去了小数警告。

这被称为旧的方式,因为C++提供了一个优越的替代方案'静态转换';这提供了一种从一种类型转换到另一种类型的更安全的方式。等效方法是(和方式,你应该这样做)

float var_x = 9.99; 
int var_y = static_cast<int>(var_x); 

这种方法可能看起来有点长篇大论,但它如不慎请求“静态投”的情况下提供更好的操控在无法转换的类型上。有关您应该如何使用静态投射的更多信息,请参阅this question

+1

我没有得到反对票?关心给一个理由? – thecoshman 2010-03-30 10:34:27

+2

我没有downvote,但它可能是由于你在C++代码中使用C风格转换。这是不好的风格 – Glen 2010-03-30 10:40:25

+0

我是?真?对不起,那是我虽然想要做他们的方式 – thecoshman 2010-03-30 10:57:37

0

我相信你可以使用强制这样做:

float f_val = 3.6f; 
int i_val = (int) f_val; 
0

最简单的方法是只分配浮到INT,例如:

int i; 
float f; 
f = 34.0098; 
i = f; 

这将截断后面浮点或一切你可以在之前将你的浮点数整圆。

9

某些浮球的尺寸可能会超过int的尺寸。 这个例子显示使用int safeFloatToInt(const FloatType &num);功能的浮球式的安全转换为int

#include <iostream> 
#include <limits> 
using namespace std; 

template <class FloatType> 
int safeFloatToInt(const FloatType &num) { 
    //check if float fits into integer 
    if (numeric_limits<int>::digits < numeric_limits<FloatType>::digits) { 
     // check if float is smaller than max int 
     if((num < static_cast<FloatType>(numeric_limits<int>::max())) && 
      (num > static_cast<FloatType>(numeric_limits<int>::min()))) { 
     return static_cast<int>(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<int>::max(); 
     } 
    } else { 
     //It is safe to cast 
     return static_cast<int>(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; 
} 

结果:

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

根本不编译(cxx11) – dgrat 2015-10-12 12:18:59

3

退房升压NumericConversion库。它将允许明确地控制你想如何处理溢出处理和截断等问题。

0

我想补充一件事。有时候,会有精确度损失。转换前可能需要先添加一些epsilon值。不知道为什么这样工作...但它的工作。

int someint = (somedouble+epsilon); 
2

在大多数情况下(长的花车,很长很长的double和long double):

long a{ std::lround(1.5f) }; //2l 
long long b{ std::llround(std::floor(1.5)) }; //1ll