[英]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.