Accept a floating point value and print it with 20 width space and round off to 4 decimal places.
This problem combines two important formatting concepts:
setw(20)
- Sets the output width to 20 characters (right-aligned by default)setprecision(4)
- With fixed
, shows exactly 4 decimal placesfixed
- Prevents scientific notation and enables decimal precision📚 Want to learn more about setw()
?
How it works together:
Order matters!
fixed
→ setprecision(4)
→ setw(20)
Key Differences:
setw()
- Affects total width (including decimal point and digits)setprecision()
- Only affects digits after decimal pointsetw()
is temporary - applies only to next outputfixed
and setprecision()
are persistent#include <iostream>
#include <iomanip>
using namespace std;
int main() {
long double f;
cin >> f;
// fixed: Prevents scientific notation
// setprecision(4): Exactly 4 decimal places
// setw(20): Total width of 20 characters
cout << fixed << setprecision(4) << setw(20) << f;
return 0;
}