2010-03-30 105 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