2010-12-13 39 views
2

如何獲取數字的小數點?例如:
如果我有1.5如何獲得5號碼?獲取小數點

+0

對不起,我不明白的問題。你想要處理的是什麼類型?你有一個double,你想在逗號後的十進制表示變成一個int?你想有5存儲在一個int?爲什麼5而不是50? – Benoit 2010-12-13 10:33:13

+0

@Benoit,因爲我只對點後的第一個數字感興趣。 – 2010-12-13 10:34:09

+0

...爲什麼你需要「點後的第一個數字」,但沒有別的? – 2010-12-13 10:37:07

回答

4
int result = static_cast<int>(fmod(number, 1)*10); 

編輯:或者更簡單,可能更快:

int result = static_cast<int>(number*10)%10; 

編輯:使其也工作了負數,你可以這樣做:

int result = abs(static_cast<int>(number*10))%10; 
+0

你已經按時擊敗了我;) – BlackBear 2010-12-13 10:45:40

+0

如果我們不知道小數點的位置,我的意思是如何解決這個問題,對於任何給定的浮點數如12.76,164.7,8759.128756等等。 – Rasoul 2012-11-02 00:36:26

+0

@Rasoul:這個解決方案在任何情況下都可以工作,它總是給你第一個十進制數字。 – 2012-11-02 08:53:32

2

說你有x=234.537

floor(x*10)給你2345

你那麼只需要10

因此,要獲得一個除法的餘數:

int firstDecimal = floor(x*10)%10

+1

'int firstDecimal = floor(x * 10)%10'甚至不會編譯。 'floor'是浮點類型,但'%'需要非浮點數(int,unsigned等)。 – 2010-12-13 10:44:48

+0

我沒有給出特定語言的答案。這可以用於幾乎任何語言。您可能需要在C++中進行一些強制轉換。 – nico 2010-12-13 12:29:33

1

這裏:

(int) (n*10) % 10 
+0

如果n是負數?它會起作用嗎? – Nawaz 2010-12-13 10:56:01

+0

@Nawaz:可能或不會。取決於平臺(硬件)。 – 2010-12-13 11:01:54

+0

我在想同樣的事情! – Nawaz 2010-12-13 11:04:01

1

有一個很好的簡單的方法來做到這一點。

int GetFirstDecimalPlace(float f) 
{ 
    const float dp = f - floorf(f); // This simply gives all the values after the 
             // decimal point. 
    return static_cast<int>(dp * 10.0f); // This move the value after the decimal 
              // point to before it and then casts to an 
              // int losing all other decimal places. 
} 
1

使用沒有宏/功能負數工作方式調用:

n < 0 ? (int) (-n * 10) % 10 : (int) (n * 10) % 10 
+0

太複雜了。可以是'static_cast ((n> = 0?n:-n)* 10)%10'。但我沒有看到任何理由,爲什麼不叫abs()。 – 2010-12-13 11:17:15

+0

你說得對,這樣就簡單多了。除了性能方面的原因,沒有理由不全部使用abs(),但這可以忽略不計。我只是想用這種語言提供的工具來展示一種方法,而不是圖書館。順便說一句,使用static_cast 而不是(int)的任何理由? – 2010-12-13 11:50:45

+0

謝謝你的回答。使用static_int代替just(int)的原因是爲了在程序中標出執行顯式轉換的地方。這是出於可讀性的原因。 – 2010-12-13 11:57:24