Hi, I am trying to use a command setprecision from the <iomanip.h> header.

It works well when i declare the number of decimals to display to the right of the decimal point, however i am attempting to have the user input how many places of precision they want. So far it will only out put about 15 characters on the last output no matter what my input is...

I am new to c++ and any help would be awesome.
Thanks
-Scott

#include <iostream.h>
#include <iomanip.h>
int main()
{
    float x,y;
    cout << "Enter two float-point number (Example: 2.415 1.312)\n";
    cin >> x >> y;
       
    float z=x*y;      
    cout << z << '\n';
    cin.ignore(50, '\n');
    cout << "how many digits do you want to display to the right of the decimal point?\n";

    char q;
    cin >> q;
    cin.ignore(50, '\n');
    cout << setprecision (q) << z << endl;
    system("PAUSE");
    return 0;
}

Don't use the old and outdated header files - instead, use iostream and iomanip:

#include <iostream>
#include <iomanip>
using namespace std;

Secondly, your code isn't going to work as expected because you're inputting the amount as a char . char does happen to be an int, but if you look at an ascii table, you'll find that '1' is not equal to the actual value 1. Thus, you are giving setprecision() far larger values than you expect.

Change 'q' to an int, which should fix your problem. Better yet, avoid the cin >> method and use cin.getline() and write your own parser, which although more lengthy is more robust and avoids problems like a \n left in the stream after reading. Don't worry about doing this now, as your program is relatively small.

A few points:

  • Dont use the old style of header inclusion (ie the .h one). Include your headers as
#include <iostream> 
          #include <iomanip>
          using namespace std ;
  • Don't use system("pause") to pause your program. Its a non portable way and takes way too much of resources to just pause the program (OS calls and all that). Better use cin.get() to pause for user input.
  • Any specific reason why you have chosen q to be character type ? That's where your problem lies. Even if the user enters 1, it would be taken as '1' (character 1) and its decimal equivalent would be 49. So in the end, you set the stream precision to 49.
  • Change the data type of q from char to int or something like that and you should be fine.

Hope it helped, bye.

PS: Grr..Joey beat me to it.

Good for your compiler! The stored value of a floating point number has a limited precision, probably 50 or 60 bits. This is equivalent to a certain number of decimal digits, say about 15. If the computer were to give you a 20 decimal digit answer the last few digits would be random garbage. Your problem isn't reading in the precision. In fact, if you set the precision to 50 in the program you'd get the same result.

This article has been dead for over six months. Start a new discussion instead.