-2

I'm brand new to programming so please answer in simple terms. I'm trying to print a double. The program ask the user to input as many digits of pi as he can remember, and then it is supposed to print it back to him. But it always prints back 6 decimal places. I need it to print the amount of decimals that were originally put in. so 3.14 is to decimals, while 3.141592654 is 9. so it prints what was put in.

abligh
  • 24,573
  • 4
  • 47
  • 84
el_m
  • 1
  • 1

4 Answers4

4

You need a combination of std::fixed followed by std::precision

Like this:

  double f =3.14159;
  std::cout << std::fixed;
  std::cout << std::setprecision(5) << f << '\n'; // prints 5 decimals
  std::cout << std::setprecision(9) << f << '\n'; // prints 9 decimals

Now what to pass to std::setprecision() as an argument needs to be calculated from the input you are getting.

CinCout
  • 9,486
  • 12
  • 49
  • 67
  • 3
    I don't understand how this was upvoted four times, as it clearly does not answer the question... "I need it to print the amount of decimals that were originally put in" - Your solution clearly doesn't do that... – leemes Sep 14 '15 at 12:37
3

Numbers are numbers, not strings. They have actual precision governed by their type (float, double etc).

You cannot "remember" the logical precision originally provided, unless you take input as string, count the precision yourself, then convert to a number.

Then you use formatting options to reproduce that precision level in the output.

Alternatively, just stick with strings.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
2

For this specific case only (comparing how precise was the entered pi), use a std::string rather than a double. If someone who knows a couple of thousands of digits uses your program, the double-precision floating point variable will not be precise enough for a comparison. You will have to store a reference pi as a string too.

Incidentally, with this approach you will no longer have the issue of remembering how many decimal places were entered.

Maksim Solovjov
  • 3,147
  • 18
  • 28
0

You might want to investigate the differences between decimal and binary representations of numbers.

Your user enters a decimal representation, i.e. each symbol represents a digit from 0 to 9.

On the other hand, a double is a binary representation.

Some numbers can be expressed with a decimal representation but have no equivalent in binary representation. For instance you cannot express 0.3 with a finite number of binary symbols.

That's why you should keep your input as decimal, for instance by using a string.

ZunTzu
  • 7,244
  • 3
  • 31
  • 39