Accept a floating point value and precision value and print the floating point value according to the precision given.
The Power of Variable Precision!
Unlike previous questions where we used fixed values like setprecision(2)
or
setprecision(4)
, this problem shows that setprecision()
can
accept variables too!
setprecision(a)
where a
is a variable
lets users control output precision dynamically at runtime!
How it works:
Input | Precision | Output |
---|---|---|
15.87 |
6 |
15.870000 |
15.87 |
2 |
15.87 |
15.87654321 |
3 |
15.877 |
Why is this useful?
Remember:
fixed
+ setprecision(n)
= exactly n
digits after decimaln
places📚 Related Questions:
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
long double f;
int a;
// Read floating-point value and precision
cin >> f >> a;
// fixed: Use fixed-point notation
// setprecision(a): Use variable 'a' for precision!
cout << fixed << setprecision(a) << f;
return 0;
}