In this C++ program, we'll learn the use of float data type that handles floating point numbers. There's another similar data type called double which is also same as float but can handle double the precision of float.
Purpose
Write a program to accept two floating point numbers from a user and print their product on screen.
// Program to accept two numbers and print their product
#include <stdio.h>
using namespace std;
int main()
{
float num1, num2, product;
// Display request for first number
printf("Enter the first number : ");
scanf("%f", &num1); // Get first number and store it in num1 variable
// Display request for second number
printf("Enter the second number : ");
scanf("%f", &num2); // Get second number and store it in num2 variable
// Multiply the two numbers
product = num1 * num2;
// Print the product of the numbers
printf("Product of numbers = %f", product);
return 0;
}
Explanation
You must have observed the program is somewhat similar to the program we wrote in the previous lesson. The only minor difference is that here we are using the float
data type instead of int
and the plus (+) operator/sign
is replaced with product (*) operator. Everything else remains same.
Again, we have made use of the scanf()
& printf()
functions. These functions accept the data type is the input and output as well and so we have supplied %f
for float and similary we use %d
for integers. We haven't used the iostream library here as we haven't used cout
or cin
constructs.