Domanda

I have this problem. I get the result from the function double sin(double x)of the library cmath. I want to write this result in a file declared as ofstream fileand I want that when the result is close to zero, write 0.000000 and not 1.22465e-16. For example, I tried:

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

where the multiplication between intervaland c is about π.

But in the file is written1.22465e-16, while in the shell is written 0.000000. How can i do to get the approximation0.000000 in ofstream file? Thanks all

È stato utile?

Soluzione

If you want the same format the "%f" specifier uses (rather than the default which is "%g"), you'd use

std::cout << std::fixed;

To restore the original format, i.e., get back to using the same format as "%g" you'd use

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

Altri suggerimenti

You can check if it is below a threshold and just set it to 0

 if(fabs(x) < 1e-8) x = 0;
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top