Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

need help with setprecision manipulators...?

Status
Not open for further replies.

n0s

Programmer
Nov 3, 2004
1
US
Yes I'm doing a self study correspondence for computer science through texas tech and i need some help with a project im working on. It involves "setprecision" manipulators..

OK so here's my problem.. I'm working on a pragram that asks the user for two floating point numbers.(i got that down.) now it multiplies them and prints them to to the screen. Well i got all that but next im supposed to prompt the user for "how many digits to displayt tot the right of the decimal". Well i've been through my book and i can't find a solution. The best i'v have is using the setprecision, but i dont' know how to prompt the user to set the precision. any help would be nice....

======================
here's the code
======================

/*
Name: Project6_3.cpp
Author: William Smith
Date: 01/11/04
Description: A program that asks the user for two floating-point
numbers. The program should mulitply the numbers
together and print the product to the screen.
Next it asks the user how many digits to display to
the right of the decimal point and print the product
again with the new precision.
*/

#include <iostream.h>
#include <iomanip.h>

main()
{
float a,b,c,p;

cout << "Enter two numbers: \n";
cin >> a >> b;

c = a * b;

cout << "The product is: " << c << "\n";
cout << " \n";
cout << "Now enter the number of units to
display: ";
cin >> p;
//now here's where im stuck...!


cout << "\n";
system("pause");
return 0;
}

 
Just do a cout << setprecision(p) and then cout c like normal.

Also, <iostream.h> and <iomanip.h> are obsolete, you should include <iostream> and <iomanip> instead. All the same stuff is in there, just put in a namespace std. If you don't know what a namespace is, look it up, but you can make all of your current code work by adding the line "using namespace std;" after your includes. People say it's bad practice, but I've never seen a solid enough argument to keep me from using it.
 
What you need to do is the following:

cout << setprecision(p) << setiosflags(ios::fixed);
cout << c;

With just the setprecision it will set the most significant digits to the left of the decimal to 2. The setiosflags(ios::fixed) will set the precision to the right of the decimal.


Hyper
 
Also, setprecision() takes an int, not a float. So you should do something like this:
Code:
int iDigits = 0;
cout << "Enter the number of digits of precision:";
cin >> iDigits;

cout << setprecision( iDigits ) << setiosflags( ios::fixed );
cout << c;
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top