【发布时间】:2013-11-19 06:14:55
【问题描述】:
以下是我的控制台输入/输出。
请输入实数:-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 显示的值为 -23486.33。那么这和 cout 打印出来之间会发生什么?在我的代码中,我没有设置 cout 的精度或使其固定。
如果您有任何问题,请告诉我。
【问题讨论】:
-
需要进行一些舍入以避免输出过长。例如,最接近 IEEE 754 64 位二进制到十进制 -23486.33 是 -23486.330000000001746229827404022216796875。这可能就是您的
number的价值。 -
@PatriciaShanahan 但是,在这种情况下,为什么要将我的数字(调试器显示为 -23486.33)修剪为 -23486.3 ?即使这个数字是一个小数位数过多的数字,就像你的例子一样,为什么还要继续修剪掉一组 0 呢?
-
ostream 格式基于宽度和精度,而不是数字的值。相比之下,Java 的 Double toString 将双精度转换为最短的字符串,然后再转换回相同的双精度。它会将您的号码显示为 -23486.33。
-
@PatriciaShanahan 现在说得通了。