0

In algorithm competitions, there are sometimes problems that require the solution to keep certain amount of decimal places, for example (when keeping 2 decimal places) the output for 3 is 3.00 and the output for 3.1415926 is 3.14.

However, std::setprecision cannot meet the requirement, as it controls the amount of effective numbers instead of decimal places. For example, the following code

std::cout << set::precision(5) << 123.456;

actually produces the output

123.46

instead of the expected

123.45600

And what is really required is the exactly same output as the following printf does:

printf("%.5lf", 123.456);

So how can I keep certain amount of decimal places, instead of effective numbers, in C++? In my view, printf may not be a good idea, because personally I think printf exists in C++ only for compatibility reasons.

Yang Hanlin
  • 474
  • 1
  • 6
  • 18

0 Answers0