回答
下面是做這件事:轉換十進制爲一個字符串,並找到小數點後的字符串的大小,具體如下:
#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)
}
浮點數不提供的數點後的數字。 (它甚至不是'確切'的值,它是一個近似值。)
但是,如果你只是想讓另一個整數在屏幕上的點之後具有相同的數字位數,爲什麼不你只是數數?
這裏是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
爲什麼選票只爲我的答案...?基本上同樣的方法......? –
簡短的回答是,你不能。
首先,像double
這樣的類型在(二進制)週期後總是具有相同數量的二進制數字。這就是所謂的尾數。在雙倍情況下是53位,即二進制週期後的52位,十進制數是約15位數。有關詳細信息,您可能會看到一個IEEE_754 (double precision)
當您將雙精度型轉換爲十進制字符串時,通常情況下絕不匹配精確的十進制。例如,值0.1
無法完全用double值表示。應用四捨五入後,printf可能會顯示「0.1」。
但是,當您處理一些雙重計算時,您將會遇到像0.10000000000012
或0.09999999999987
這樣的小推導。在這種情況下你會做什麼?
還有是無關用C++雙打數學家問題:
_
0.1 is equal to 0.09
所以你的答案會是1或無窮大
你可以把小數部分作爲一個字符串。利用std::stringstream和std::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();
}
你可以使用'std :: modf()'來提取小數部分。 – HolyBlackCat
@HolyBlackCat的確。我已經更新了答案。 – Ron
- 1. Java:指定小數點後的數字
- 2. 如何找出一個數字有多少個小數?
- 3. 指定的數字是什麼數字,其中有多少個數字?
- 4. 我如何展示後只有兩個數字小數點
- 5. 如何獲得小數點後只有兩個數字
- 6. 如何讓小數點前後只有一個數字的texbox?
- 7. 陣列中有多少數字小於給定數字?
- 8. 數字格式BEST15.2允許在小數點後有多少位置在SAS中
- 9. iPhone:浮點後應該有多少個數字
- 10. 小數點後的數字固定量
- 11. 如何指定小數點分隔符
- 12. 小數點後只有2位數字?
- 13. 如何在小數點後打印最多2位數字?
- 14. 如何返回一個帶有指定小數位數的浮點數?
- 15. 有沒有辦法減少小數點後的位數?
- 16. 告訴一個浮點數在點之後要保存多少個數字
- 17. QDoubleSpinBox:如何減少小數點後的位數?
- 18. 指定號碼()小數點
- 19. 如何指定只有少數類型多態方法
- 20. 如何測試一個數字是一個整數還是小數點後只有一個零的浮點數?
- 21. Swift:如何比較CGFloat小數點後的前n個數字?
- 22. 如何返回2個小數點後的數字?
- 23. Edittext如何只能接受小數點後的兩個數字
- 24. 如何在小數點後始終顯示3個數字C#
- 25. 如何評估數字中小數點後的數字?
- 26. 格式小數用小數點後儘可能少的位數
- 27. 如何將小數點後兩位到小數點後n位?
- 28. 允許用戶在小數點前輸入最多4個字符,小數點後輸入2個數字
- 29. CSS中有多少個有效數字?
- 30. 如何找到一個特定的字符串,後跟一個數字,其間有多少個字符?
您可能能夠使用[MODF(http://www.cplusplus.com/reference/cmath/modf/)。 – Javia1492
聽起來像[XY問題](http://xyproblem.info/)。你真的想要解決什麼高水平的問題? – PaulMcKenzie
注意不要將'std :: cout << a;'與'a'的有效數字的位數混淆在屏幕上顯示的數字的數量 – user463035818