C++ Walkthrough cout.setf(ios::fixed); and cout.precision();
-
01-06-2021 - |
Domanda
/* 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 above code I just wanted to know what below two lines will really do in the above code
cout.setf(ios::fixed);
cout.precision(3);
Please do not just give me answer some explanation would be so appreciated because I'm doing a walkthrough to prepare for my final exam tomorrow.
I searched and some source says it is to set flags but really I don't get what is the concept of it and how it works
Soluzione
cout.setf(ios::fixed)
makes cout print floats with a fixed number of decimals and
cout.precision(3)
sets this number to be three.
For example, if you got a
double f = 2.5;
then
cout << f;
will print
2.500
Altri suggerimenti
Great documentation about how to format your output : Output formatting
It's always usefull when you're trying to do a command-line UI.
#include<iostream>
using namespace std;
int main(){
float large = 2000000000;
cout << large;
return 0;
}
The output will be in scientific notation as:
2e+009
In order to get the value as it is 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 as it is with default precision which is 6 for float.
2000000000.000000
You can set the precision in the above code as:
cout.precision(7);
.....
It's similar to including the manipulation library:
include :
<iomanip>
And then using the following functions
cout << fixed << showpoint;
cout << setprecision(3);