0

Here is some "pseudo" c++ code

double var = 5.5;
cout << var << endl;
double var2 = 6.0;
cout << var2 << endl;

5.5
6

The problem is that some code might expect that it's 6.0. Does someone has an idea how to change the output stream.

Okay here is some example code i tried

 double t = 6.0;
  while (t > 0.1) {
    t = t - 0.1;
    cout << setprecision(2) << t << endl;
  }

The output is

5.9
5.8
...
5.2
5.1
5
4.9
4.8
4.7
Daniel Wehner
  • 2,159
  • 1
  • 18
  • 22

2 Answers2

4

Use std::setprecision along with std::fixed:

std::cout << std::fixed << std::setprecision(1) << var2 << std::endl;

See demo : http://ideone.com/Arz85

Only std::setprecision(1) would not work. You've to use std::fixed as well.

Don't forget to include this:

#include <iomanip>

I guess you've written using namespace std in your code. If so, then don't do that. Write fully qualified names, such as std::cout, instead of cout. See these topics:

Community
  • 1
  • 1
Nawaz
  • 353,942
  • 115
  • 666
  • 851
0

Use ios_base flags, take a look at the C++ reference.

Sebastian
  • 8,046
  • 2
  • 34
  • 58