Passing C ++ cout.setf (ios :: fixed); and cout.precision ();

/* Problem 38 */ #include <iostream> using namespace std; class abc { double n; public: abc() { n = 67.5; cout << "1\n"; } abc(double num) { set(num); cout << "2\n"; } double get() const { cout<<"3\n"; return n; } virtual void set(double num) { if (num < 10) n = 10; else if (num > 100) n = 100; else n = num; cout << "4\n"; } }; class def: public abc { double m; public: def() { m = 6.2; cout << "5\n"; } def(double num1, double num2): abc(num1) { set(num2 - abc::get()); cout << "6\n"; } double get() const { cout << "7\n"; return m + abc::get(); } void set(double num) { if (num < 10 || 100 < num) m = num; else m = 55; cout << "8\n"; } }; void do_it(abc &var, double num) { cout << var.get() << '\n'; var.set(num); cout << var.get() << '\n'; } int main() { abc x(45); def y(2, 340); cout.setf(ios::fixed); cout.precision(3); do_it(x, 200); do_it(y, 253); cout << x.get() << '\n'; cout << y.get() << '\n'; return 0; } 

With the code above, I just wanted to know what below the two lines really will be in the code above

cout.setf(ios::fixed); cout.precision(3);

Please do not just give me an answer, some explanation will be so appreciated, because I am doing a step-by-step guide to prepare for my final exam tomorrow.

I searched, and some source says that it should set flags, but in fact I don’t understand what the concept is and how it works.

+7
source share
4 answers
 cout.setf(ios::fixed) 

does cout print float with a fixed number of decimal places and

 cout.precision(3) 

sets this number to three.

For example, if you received

 double f = 2.5; 

then

 cout << f; 

will print

 2.500 
+11
source

Excellent documentation on output formatting: Formatting output

It is always useful when you are trying to execute a command line interface.

+3
source

This is similar to including a manipulation library:
include:

 <iomanip> 

And then using the following functions

 cout << fixed << showpoint; cout << setprecision(3); 
0
source
 #include<iostream> using namespace std; int main(){ float large = 2000000000; cout << large; return 0; } 

The output will be in scientific notation:

 2e+009 

To get a value like this, you should use cout.setf(ios::fixed)

 #include<iostream> using namespace std; int main(){ cout.setf(ios::fixed); float large = 2000000000; cout << large; return 0; } 

The output will be the same as with a default precision of 6 for float.

 2000000000.000000 

You can set the accuracy in the above code as:

 cout.precision(7); 

.....

0
source

All Articles