从文件中读取浮点值会丢弃全部或部分小数部分
Reading floating point values from a file drops all or part of the decimal part
我需要从文件中读取浮点值。
我如何执行此操作的基本示例代码:
int main()
{
float number;
ifstream inputFile;
inputFile.open("testfile.dat");
inputFile >> number;
cout << number << endl;
return 0;
}
文件的第一行是:13212.13131。但是当我 cout 'number' 时,显示的数字是:13212.1
问题是部分小数被丢弃,而在其他情况下,所有小数都被丢弃。为什么会出现这种情况,我该如何解决这个问题?
从文件中读取数字的目的是用它进行数学计算。
尝试使用 std::setprecision()
:
cout << setprecision(14) << number << endl;
你需要
#include <iomanip>
如果这不能解决问题,您应该尝试调试它并查看实际数字是多少(13212.13131
或 13212.1
)。
首先,输出的浮点精度(std::cout
和 printf
)默认为 6 位十进制数字。您需要 std::setprecision()
才能打印更多数字。但是您将达到 float
类型的限制。
在大多数系统上,浮点数是 IEEE-754 single precision, therefore it can only store about 7 digits of significant. The nearest to 13212.13131 is 1.3212130859375E4. If you need more precision, you must use double,在大多数系统上其精度约为 15-16 位。
阅读更多:Is floating point math broken?
我需要从文件中读取浮点值。
我如何执行此操作的基本示例代码:
int main()
{
float number;
ifstream inputFile;
inputFile.open("testfile.dat");
inputFile >> number;
cout << number << endl;
return 0;
}
文件的第一行是:13212.13131。但是当我 cout 'number' 时,显示的数字是:13212.1
问题是部分小数被丢弃,而在其他情况下,所有小数都被丢弃。为什么会出现这种情况,我该如何解决这个问题?
从文件中读取数字的目的是用它进行数学计算。
尝试使用 std::setprecision()
:
cout << setprecision(14) << number << endl;
你需要
#include <iomanip>
如果这不能解决问题,您应该尝试调试它并查看实际数字是多少(13212.13131
或 13212.1
)。
首先,输出的浮点精度(std::cout
和 printf
)默认为 6 位十进制数字。您需要 std::setprecision()
才能打印更多数字。但是您将达到 float
类型的限制。
在大多数系统上,浮点数是 IEEE-754 single precision, therefore it can only store about 7 digits of significant. The nearest to 13212.13131 is 1.3212130859375E4. If you need more precision, you must use double,在大多数系统上其精度约为 15-16 位。
阅读更多:Is floating point math broken?