[英]Why does cout truncate a double?
以下是我的控制台輸入/輸出。
請輸入真實數字:-23486.33檢查的字符:9
謝謝。 您輸入的真實數字是-23486.3
我輸入的值為-23486.33,但是cout將其打印為-23486.3。 相關代碼如下:
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
// Function prototype (declaration)
string readDouble();
bool isValidDouble(string);
int main()
{
string value;
double number;
value = readDouble();
while (!isValidDouble(value)) {
cout << "The number you entered is not a valid integer." << endl;
value = readDouble();
}
number = atof(value.c_str());
cout << "Thank you." << endl
<< "The real number you entered is " << number << endl;
}
調試時,我在方法調用atof(value.c_str())l;
之后立即檢查number的值atof(value.c_str())l;
。 數字顯示值為-23486.33。 那么,這與cout打印出來之間會發生什么? 在我的代碼中,我都沒有設置cout的精度或使其固定。
如有任何疑問,請告訴我。
你有沒有嘗試過
std::cout << std::setprecision(2) << number;
查看: http : //www.cplusplus.com/reference/iomanip/setprecision/
您可以將精度設置為最大限制的兩倍。
代碼段在這里:
#include <iostream>
#include <limits>
#include <iomanip>
using namespace std;
double number = ... // your double value.
cout << setprecision(numeric_limits<double>::digits10) << number << endl;
輸出雙精度時設置精度,比較時顯式保持精度。
當您將DEC數字的字符串表示形式轉換為雙精度(浮點數表示形式)時,內存中的數據在數學上可能不等於字符串表示形式。 用浮點數表示法是最好的近似值,反之亦然。
顯示-23486.3是因為std::cout
默認只輸出6位數字。
要打印回從標准輸入中輸入的數字(轉換文本→浮點數→文本),可以將set_precision
與digits10
用作精度:
double d = -23486.33;
int precision = std::numeric_limits<double>::digits10;
std::cout << std::setprecision(precision) << d << std::endl;
顯示:
-23486.33
要打印具有全精度(通常為皈依浮點數→文本→浮數)一個數字,你可以使用set_precision
與max_digits10
精密:
double d = -23486.33;
int precision = std::numeric_limits<double>::max_digits10;
std::cout << std::setprecision(precision) << d << std::endl;
顯示:
-23486.330000000002
此處的打印編號不同,因為-23486.33在IEEE編碼中沒有確切的表示形式(以2為基數而不是10為基數)。
有關digits10
和max_digits10
更多詳細信息,您可以閱讀:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.