Float Multiplication in C++

Multiply two floats in C++ and print two decimal places with setprecision. Needs iomanip.

BeginnerBasic ProgramsExample 7 of 14
float-multiplication.cpp
1#include <iostream>
2#include <iomanip>
3using namespace std;
4
5int main() {
6 float num1, num2, product;
7
8 cout << "Enter first number: ";
9 cin >> num1;
10
11 cout << "Enter second number: ";
12 cin >> num2;
13
14 product = num1 * num2;
15
16 cout << fixed << setprecision(2);
17 cout << "Product of " << num1 << " and " << num2 << " is: " << product << endl;
18
19 return 0;
20}

Output

Enter first number: 3.5
Enter second number: 2.5
Product of 3.5 and 2.5 is: 8.75

What's going on

This C++ program multiplies two float values and prints the product to two decimal places.

#include <iomanip>

That's fixed and setprecision. Skip it and those names don't compile.

float num1, num2, product;

About 7 decimal digits of precision. 0.1 + 0.2 in binary float is why money-in-float goes wrong. Use double when the extra digits matter.

cin >> num1; then cin >> num2;

Letters leave the stream failed. Same as integer input.

product = num1 * num2;

Sample: 3.5 * 2.5 = 8.75.

cout << fixed << setprecision(2);

Needs the iomanip include. fixed means "this many digits after the dot." Without fixed, setprecision(2) means two significant digits, so 8.75 might print as 8.8 or 8.75e+00 depending on the value. People mix those up constantly.

Then the product line prints Product of 3.5 and 2.5 is: 8.75.

float is enough for this demo. Don't store currency in it.