简体   繁体   English

C ++:在ofstream文件中写一个双近似值,例如printf(“%f…)

[英]C++: write a double approximation in ofstream file, like printf("%f…)

I have this problem. 我有这个问题。 I get the result from the function double sin(double x) of the library cmath. 我从库cmath的函数double sin(double x)中得到结果。 I want to write this result in a file declared as ofstream file and I want that when the result is close to zero, write 0.000000 and not 1.22465e-16 . 我想将此结果写入声明为ofstream file并且我希望当结果接近于零时,写入0.000000而不是1.22465e-16 For example, I tried: 例如,我尝试过:

`double x=sin(interval*c);
 file<<"value:"<<x;
 printf("value:%f",x);`

where the multiplication between interval and c is about π. intervalc之间的乘积约为π。

But in the file is written 1.22465e-16 , while in the shell is written 0.000000 . 但是在文件中写入1.22465e-16 ,而在shell中写入0.000000 How can i do to get the approximation 0.000000 in ofstream file? 我如何才能获得Ofstream文件中的近似0.000000 Thanks all 谢谢大家

If you want the same format the "%f" specifier uses (rather than the default which is "%g" ), you'd use 如果要使用"%f"说明符使用的相同格式(而不是默认的"%g" ),则可以使用

std::cout << std::fixed;

To restore the original format, ie, get back to using the same format as "%g" you'd use 要恢复原始格式,即恢复使用与"%g"相同的格式

std::cout << std::defaultfloat; // C++11
std::cout.setf(std::ios_base::fmtflags(), std::ios_base::floatfield); // pre C++11

您可以检查它是否低于阈值并将其设置为0

 if(fabs(x) < 1e-8) x = 0;

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

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