Search code examples
c++printingfloating-pointdoublecout

C++ How to use relative error with `cout`?


While preparing for my first ever coding interview I found a question where I was requested to print a double number with an absolute or relative error of 10^(-6).

How can I do something like that with cout?

double test_var; // Holding Some value which changes according to my program.
cout << test_var << endl;

Plus, In the expected output I saw numbers like 1000.00 how can I print those .00 too?


Solution

  • You could have used std::setprecision.

    #include <iostream>
    #include <iomanip>
    int main()
    {
      double f =3.14159;
      std::cout << std::setprecision(5) << f << '\n'; //prints 3.1416
      std::cout << std::setprecision(9) << f << '\n'; //prints 3.14159
      std::cout << std::fixed;   //Modifies the default formatting for floating-point input/output.  
      std::cout << std::setprecision(5) << f << '\n'; //prints 3.1416
      std::cout << std::setprecision(9) << f << '\n'; //prints 3.141590000   
    }