Multiply two decimal numbers and print the product with a precision of 2 decimal places.
What You'll Learn:
// 1. Why long double?
long double f1, f2; // Handles very large decimals
// 2. Read two decimal numbers
cin >> f1 >> f2; // Space-separated input
// 3. Format and print the product
cout << fixed // Fixed-point notation
<< setprecision(2) // 2 decimal places
<< f1 * f2; // Calculate and print
Type | Size | Precision | Range |
---|---|---|---|
float |
4 bytes | ~7 digits | ±3.4 × 10^38 |
double |
8 bytes | ~15 digits | ±1.7 × 10^308 |
long double |
12-16 bytes | ~19 digits | ±1.1 × 10^4932 |
long double
ensures
we can handle very large decimal values and their multiplication without losing accuracy.
double num = 1234567.89;
// Without fixed (might use scientific notation)
cout << setprecision(2) << num;
// Output: 1.2e+06 (scientific notation!)
// With fixed (always decimal format)
cout << fixed << setprecision(2) << num;
// Output: 1234567.89 (decimal format!)
fixed
before setprecision()
when you want exact decimal places. Without fixed
, large numbers might switch to
scientific notation!
// Input: 2.24 3.56
f1 = 2.24
f2 = 3.56
// Multiplication:
f1 * f2 = 7.9744 // Actual result
// With setprecision(2):
7.97 // Rounded to 2 decimal places
// Example 2: 125.58 * 78.65 = 9876.8670
// Output: 9876.87
The <iomanip>
library provides I/O manipulators:
setprecision(n)
- Set decimal precisionsetw(n)
- Set field widthsetfill(c)
- Set fill characterfixed
- Use fixed-point notationscientific
- Use scientific notationleft/right
- Set alignmentThis is one of the most commonly used libraries for formatted output in C++!
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
long double f1, f2;
cin >> f1 >> f2;
cout << fixed << setprecision(2) << f1 * f2;
return 0;
}