2017-08-30 70 views
1

有沒有什麼辦法可以確定在小數點後的雙數中有多少個數字。例如double a=3.14259如何指定小數點後有多少個數字?

如果我現在新建一個int b,如何使b的值等於小數點後的數字a

+1

您可能能夠使用[MODF(http://www.cplusplus.com/reference/cmath/modf/)。 – Javia1492

+1

聽起來像[XY問題](http://xyproblem.info/)。你真的想要解決什麼高水平的問題? – PaulMcKenzie

+1

注意不要將'std :: cout << a;'與'a'的有效數字的位數混淆在屏幕上顯示的數字的數量 – user463035818

回答

0

下面是做這件事:轉換十進制爲一個字符串,並找到小數點後的字符串的大小,具體如下:

#include <iostream> 
#include <string> 

int main() 
{ 
    double a = 3.14259; 
    std::string a_string = std::to_string(a); 
    a_string.erase (a_string.find_last_not_of('0') + 1, std::string::npos); //Get rid 
                     //of extra zeroes 
    std::cout << a_string.substr(a_string.find('.') + 1).size() << "\n"; 
    //Print the size of the substring of the original string from the decimal point (here 5) 
} 
-2

浮點數不提供的數點後的數字。 (它甚至不是'確切'的值,它是一個近似值。)

但是,如果你只是想讓另一個整數在屏幕上的點之後具有相同的數字位數,爲什麼不你只是數數?

這裏是Python代碼:

a = 4.0/7 
# a is 0.5714285714285714 
b = str(a) 
# b (str(a)) is 0.571428571429, different with a. 
nod = len(b[b.index('.'):]) 
_c = 9.0/7 
c = float(int(_c * 10 ** nod))/10 ** nod 
+0

爲什麼選票只爲我的答案...?基本上同樣的方法......? –

2

簡短的回答是,你不能。

首先,像double這樣的類型在(二進制)週期後總是具有相同數量的二進制數字。這就是所謂的尾數。在雙倍情況下是53位,即二進制週期後的52位,十進制數是約15位數。有關詳細信息,您可能會看到一個IEEE_754 (double precision)

當您將雙精度型轉換爲十進制字符串時,通常情況下絕不匹配精確的十進制。例如,值0.1無法完全用double值表示。應用四捨五入後,printf可能會顯示「0.1」。

但是,當您處理一些雙重計算時,您將會遇到像0.100000000000120.09999999999987這樣的小推導。在這種情況下你會做什麼?

還有是無關用C++雙打數學家問題:

     _ 
    0.1 is equal to 0.09 

所以你的答案會是1或無窮大

0

你可以把小數部分作爲一個字符串。利用std::stringstreamstd::string

#include <iostream> 
#include <string> 
#include <sstream> 
int main(){ 
    double whole = 3.14259; 
    auto fractionalno = whole - static_cast<long>(whole); // or use std::modf() 
    std::stringstream ss; 
    ss << fractionalno; 
    std::string s = ss.str(); 
    s.erase(0,2); 
    std::cout << "The number of digits is: " << s.size(); 
} 
+0

你可以使用'std :: modf()'來提取小數部分。 – HolyBlackCat

+0

@HolyBlackCat的確。我已經更新了答案。 – Ron

相關問題