以更精确的方式将数字写入文件 - C ++ [英] Writing numbers to a file with more precision - C++
问题描述
我写了一些参数(所有类型 double
)到一个文件,用于执行一些复杂的计算。我写的参数到文件像这样:
I wrote some parameters (all of type double
) to a file for use in performing some complex computations. I write the parameters to the files like so:
refStatsOut< SomeParam:< value_of_type_double< endl;
其中 refStatsOut
是 ofstream
参数。有四个这样的参数,每个类型 double
。我看到写入文件与其实际值不同(在精度损失方面)。例如,如果 value_of_type_double
的值为-28.07270379934792,那么我在文件中看到的是-28.0727。
refStatsOut << "SomeParam:" << value_of_type_double << endl;
where refStatsOut
is an ofstream
parameter. There are four such parameters, each of type double
. What I see as written to the file is different from what its actual value is (in terms of loss of precision). As an example, if value_of_type_double
had a value -28.07270379934792, then what I see as written in the file is -28.0727.
此外,一旦计算和编写了这些统计数据,我运行使用这些统计信息的不同程序。文件被读取,并且值最初存储为 std :: strings
,然后通过<$ c转换为 double
$ c> atof 函数。这导致我在上面显示的值,并进一步废除计算。
Also, once these stats have been computed and written I run different programs that use these statistics. The files are read and the values are initially stored as std::strings
and then converted to double
via atof
functions. This results in the values that I have shown above and ruins the computations further down.
我的问题是这样:
1.是否有办法增加可以写入值的分辨率( double
等)到一个文件,以便不会丢失任何精度?
2.这也可能是一个问题 std ::字符串
到 double
转换 atof
?如果是这样,我可以使用什么其他功能来解决这个问题?
My question is this:
1. Is there a way to increase the resolution with which one can write values (of type double
and the like) to a file so as to NOT lose any precision?
2. Could this also be a problem of std::string
to double
conversion with atof
? If so, what other function could I use to solve this?
P.S:请让我知道这个问题的一些细节不清楚。
P.S: Please let me know in case some of the details in this question are not clear. I will try to update them and provide more details.
推荐答案
您可以使用 setprecision 函数。
You can use the setprecision function.
这篇关于以更精确的方式将数字写入文件 - C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!