2015-12-07 27 views
-1

說我有:我如何將一個float浮點到一個int?

55.3 and want 55 
55.6 and want 56 
81.1 and want 81 
etc. 

我一直在嘗試使用round()功能,但它似乎一直給我的最高值,爲所有小數位。

+0

請參閱http://www.tutorialspoint.com/c_standard_library/c_function_floor.htm –

+0

「它似乎不斷給我所有小數位的最高值」 - 您是什麼意思? – Amadan

+0

我將值存儲在float x變量中,當我執行round(x)時,它只會給我所有下一個最高的int – johnnysparks13

回答

2

在過去的日子裏,我們曾經說過int the_int = (int)(some_double + 0.5);(顯然要小心,如果你正在處理負值)。

+0

我還是這麼說。 – nicomp

+0

爲什麼'round()'不起作用? – juanchopanza

+0

@juanchopanza否 - 'round()'應該工作。我認爲它曾經是爲了避免引入-lm,但我可能是錯的 - 也許有人認爲'round()' – John3136

1

了一大半增加的幅度和截斷:

int round_up_or_down(double x) 
{ 
    return x > 0 ? x + 0.5 : x - 0.5; 
} 

此分配實際間隔均勻:

  • ...
  • [-1.5, -0.5) => -1
  • [-0.5, +0.5) => 0
  • [+0.5, +1.5) -> +1
  • ...
+0

[Demo](https://ideone.com/Ae0xVj) –

+0

但是round()有什麼問題? – juanchopanza

+0

@juanchopanza:沒有什麼,'round'很好 - 它與這個公式有着不同的對稱性,儘管('round'有大約0的反射對稱性,我的平移對稱性)。 –

3

OP沒有發佈失敗的代碼。某些OP編碼不正確。

使用round()轉換爲int前一個double圓的正確的方法。當然它必須在範圍內。

#include <math.h> 
#include <assert.h> 

int round_to_int(double x) { 
    x = round(x); 
    assert(x >= INT_MIN); 
    assert(x < (INT_MAX/2 + 1)*2.0); 
    return (int) x; 
} 

有關assert() s的詳細信息,請參閱How to test for lossless double/integer conversion?

爲什麼不使用(int)(x + 0.5);

1)負數不合格。

2)double只能比0.5小,因爲x + 0.5可以舍入爲1.0

3)當int精度超過double,值,其中至少顯著位爲0.5或1.0,x+0.5可以到下一個整數。

4)沒有經驗,沒有範圍檢查。

相關問題