← Back

15. Dynamic Precision Control

Easy

📝 Problem

Accept a floating point value and precision value and print the floating point value according to the precision given.

Input Format:
Accept one floating point and one integer value
Output Format:
print the floating point value according to the given precision
Constraints:
3.4E-4932 to 1.1E+4932
💡 Dynamic Precision with Variables

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!

🎯 Key Concept: 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?

  • ✅ User can decide how many decimal places they need
  • ✅ Flexible formatting for different use cases
  • ✅ Same number can be displayed with different precision
  • ✅ Great for scientific calculations, financial apps, etc.

Remember:

  • fixed + setprecision(n) = exactly n digits after decimal
  • If number has fewer decimals, zeros are added (padding)
  • If number has more decimals, it's rounded to n places

📚 Related Questions:

Examples

Sample Input 1:
Input:
15.87 6
First value: 15.87 (floating point)
Second value: 6 (precision - decimal places)
Sample Output 1:
Output:
15.870000
15.87 displayed with 6 decimal places (zeros padded)
Another Example:
Input:
123.456789 3
Output:
123.457
123.456789 rounded to 3 decimal places
One More Example:
Input:
3.14 10
Output:
3.1400000000
3.14 displayed with 10 decimal places (8 zeros added)
Solution.cpp
#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;
}