#include <iostream>
#include <iomanip>
using namespace std;
int main() {
float num1, num2, product;
cout << "Enter first number: ";
cin >> num1;
cout << "Enter second number: ";
cin >> num2;
product = num1 * num2;
cout << fixed << setprecision(2);
cout << "Product of " << num1 << " and " << num2 << " is: " << product << endl;
return 0;
}Output
Enter first number: 3.5 Enter second number: 2.5 Product of 3.5 and 2.5 is: 8.75
Float Multiplication in C++
This program teaches you how to multiply two decimal (floating-point) numbers in C++. It also shows how to control the number of digits after the decimal point in the output. This is very useful when dealing with money, measurements, or scientific values.
1. Header Files
The program uses two header files:
-
#include <iostream>
This allows the program to use cout and cin for input and output. -
#include <iomanip>
This adds formatting tools like setprecision() and fixed, which help us control how decimal numbers appear on the screen.
2. Declaring Float Variables
Inside main(), we have:
float num1, num2, product;
- float is a data type used for decimal numbers (numbers with a decimal point).
- num1 stores the first decimal number.
- num2 stores the second decimal number.
- product stores the result of multiplying num1 and num2.
float is lighter and faster than double, which is why beginners often start with it.
3. Taking Input From the User
The program asks the user to enter two decimal numbers:
cout << "Enter first number: ";
cin >> num1;
cout << "Enter second number: ";
cin >> num2;
The user types values like 3.5 and 2.5, which are stored in num1 and num2.
4. Performing Multiplication
The program multiplies the two numbers:
product = num1 * num2;
The * operator performs multiplication.
If num1 = 3.5 and num2 = 2.5, then product = 8.75.
5. Formatting the Output
Before printing, the program sets formatting:
cout << fixed << setprecision(2);
fixed→ shows numbers in normal decimal form (not scientific notation)setprecision(2)→ shows exactly 2 decimal places
This ensures the output looks clean and professional.
6. Displaying the Result
The final output:
cout << "Product of " << num1 << " and " << num2 << " is: " << product << endl;
If the user entered 3.5 and 2.5, the output will be:
Product of 3.5 and 2.5 is: 8.75
Summary
- float is used for decimal numbers
- The * operator multiplies two numbers
- iomanip header provides formatting tools
- setprecision() controls decimal places
- This is essential for working with real-world calculations