Skip to main content
gamedev.net
🔒 Locked

setprecision(int p)

Started by Hentai 2 replies 800+ views
Original Post
Hentai
Hentai
Hi! I''m testing the setprecision and would like to have 3 decimals instead of 3 If I input 3 and 4 in the program the output is 21.2 I want the output to have 3 significant figures (output: 21.206) I''m using Visual C++ 6.0 with unmodified standard libaries The code: #include <iostream.h> #include <iomanip.h> #include <math.h> #define PI 3.1415929 double d, l, v; void main() { cout << "d (dm) : "; cin >> d; cout << "l (dm) : "; cin >> l; double h, r; r = d/2; h = l - d; v = 4*PI*r*r*r/3 + PI*r*r*rh; cout << ios:fixed << setprecision(3); // something is wrong cout << "v: = " << v << "\n"; cin.get(); cin.get(); }
eh va? :P
Oluseyi
Oluseyi
First, may I suggest using the Standard C++ Libraries (they lack the ".h" extension: <iostream>, <math>, etc)? That may clear up implementation inconsistencies between vendors.

Secondly, I suggest you take a look at the setprecision documentation to see what it actually does. Here''s an excerpt:
quote:
smanip setprecision ( int n );

Set precision
  Sets the precision to be used by output operations as by a call to stream''s member precision(n)
  The precision determines the maximum number of digits that shall be output on insertion operations to express floating-point values, counting both the digits before and after the decimal point.
  You must include <iomanip> to use this manipulator.

In other words, precision does not specify the number of decimal places, but the number of digits overall.
SiCrane
SiCrane
Oluseyi: The C++ version of <math.h> is <cmath> not <math>

Hentai: I don''t think there''s any way to do what you want using iostreams. You''ll have to fall back to C style printf functions.
e.g.: printf("v = %.3f\n", v);

Also, I think the value of pi you are using is off in the last digit.
-silencer-
-silencer-
cout << ios:fixed << setprecision(3); // something is wrong

Change the that line to this:

cout << setiosflags( ios::fixed | ios::showpoint) << setprecision(3);

You're also missing a * between the rh in this line:
v = 4*PI*r*r*r/3 + PI*r*r*rh;

Your Pi value is slightly off.. here's the 25 decimal version:
3. 14159 26535 89793 23846 26433
You'll want to use 3.1415927

The rest of the code is fine and runs correctly (assuming your equation for v is correct) in MS Visual C++ 6. You need two :'s in the scope resolution - I always used fixed and showpoint for this kind of output. Hope that helps.

(silencer)

[edited by - -silencer- on March 20, 2003 4:54:41 AM]

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.