简体   繁体   English

从文件中读取浮点值将删除全部或部分小数部分

[英]Reading floating point values from a file drops all or part of the decimal part

I need to read floating-point values from a file. 我需要从文件中读取浮点值。

Basic sample code of how I do this: 我如何执行此操作的基本示例代码:

int main() 
{
    float number;
    ifstream inputFile;

    inputFile.open("testfile.dat");

    inputFile >> number;

    cout << number << endl;

    return 0;
}

The first line in the file is: 13212.13131. 文件中的第一行是:13212.13131。 But when I cout 'number' the displayed number is: 13212.1 但是,当我单击“数字”时,显示的数字是:13212.1

The problem is part of the decimal gets dropped and in other cases all of it gets dropped. 问题是小数部分被丢弃,而在其他情况下,所有小数都被丢弃。 Why does this happen, and how can I solve this problem? 为什么会发生这种情况,我该如何解决这个问题?

The point of reading the number from the file is to do mathematical calculations with it. 从文件中读取数字的目的是对其进行数学计算。

First, floating-point precision on output (for both std::cout and printf ) is 6 decimal digits by default. 首先,默认情况下,输出(对于std::coutprintf )的浮点精度为6个十进制数字。 You need std::setprecision() to get it print more digits. 您需要std::setprecision()使其输出更多数字。 But you'll then get to the limit of float type. 但是,您将达到float类型的极限。

On most systems float is IEEE-754 single precision , therefore it can only store about 7 digits of significant. 在大多数系统上,float是IEEE-754单精度 ,因此它只能存储大约7位有效数字。 The nearest to 13212.13131 is 1.3212130859375E4 . 最接近13212.13131的是1.3212130859375E4 If you need more precision, you must use double , which has about 15-16 digits of precision on most systems. 如果需要更高的精度,则必须使用double ,在大多数系统上, double的精度约为15-16位。

Read more: Is floating point math broken? 阅读更多: 浮点数学运算是否中断?

Try using std::setprecision() : 尝试使用std::setprecision()

cout << setprecision(14) << number << endl;

You will need to 您将需要

#include <iomanip>

If that doesn't solve it you should try debugging it and see what the number actually is ( 13212.13131 or 13212.1 ). 如果仍不能解决问题,则应尝试对其进行调试,然后查看实际数字( 13212.1313113212.1 )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM