Input of real numbers
You can enter several real variables from the input stream and write them into variables in the standard way:
double x, y;
cin >> x >> y;
The first number falls into the x variable, the second into y variable.
Output of real numbers
By default,
cout
in C++ outputs 6 decimal places for real numbers. This means that unless otherwise specified, a real number will be outputed to 6 digits. If the number has less digits after the decimal point, the missing digits will be replaced by zeros. If the number contains more digits after the decimal point, it will be rounded to 6.
If you do not explicitly specify the output
precision
using the
setprecision
function or using the
fixed
flag, the number will be output with that precision. For example,
81220.545
is rounded to
81220.5
, since the last sign is "5" in the fifth decimal place (the 6th digit).
The output format can be customized. To do this, use the additional library
iomanip
- manipulators that control the output.
The
fixed
manipulator is used for fixed-point output, and the
scientific
manipulator is used for scientific output. Then you need to define the number of digits in the fractional part with the
setprecision()
manipulator. With the
setw()
manipulator you can set the total number of positions to output a number.
Example
#include<iomanip>
...
double x = 1.0/6;
// set to output 9 digits in the fractional part
cout << fixed << setprecision (9);
cout << setw(12) << x << endl;
Output
_0.166666672
All operators can be written in one line:
cout << fixed << setprecision(9) << setw(12) << x << endl;
To be sure that the output is accurate, use either a fixed
format, with the default number of decimal places
cout << fixed << x << endl;