C Language Examples - Multiply Two Floating-Point Numbers
Enter two floating-point numbers and calculate their product.
Example 1
#include
int
main
(
)
{
float
num1
,
num2
,
product
;
printf
(
"Please enter the first floating-point number: "
)
;
scanf
(
"%f"
,
&
num1
)
;
printf
(
"Please enter the second floating-point number: "
)
;
scanf
(
"%f"
,
&
num2
)
;
product
=
num1
num2
;
printf
(
"%.2f times %.2f equals %.2f\n"
,
num1
,
num2
,
product
)
;
return
0
;
}
Running result:
请输入第一个浮点数: 3.4
请输入第二个浮点数: 5.6
3.40 乘于 5.60 等于 19.04
Analysis:
In the example above, we first declare three variables, num1, num2, and product, used to store the two input floating-point numbers and their product, respectively.
Then we use the printf and scanf functions to interact with the user, receiving the two floating-point numbers they enter.
Next, we assign the result of multiplying num1 and num2 to the product variable.
Finally, we use the printf function to print the computed result.
Note that the %.2f format specifier limits the output floating-point number to two decimal places.
The following example uses scanf() to accept two floating-point numbers from the user at the same time:
Example 2
#include
<
stdio.h
int
main
(
)
{
double
firstNumber
,
secondNumber
,
product;
printf
(
"
Enter two floating-point numbers:
"
)
;
// The user enters two floating-point numbers
scanf
(
"
%lf %lf
"
, &
firstNumber
, &
secondNumber
)
;
// Multiply the two floating-point numbers
product
=
firstNumber
secondNumber
;
// Output the result, with %.2lf keeping two decimal places
printf
(
"
Result = %.2lf
"
,
product
)
;
return
0
;
}
Running result:
输入两个浮点数: 1.2 2.345
结果 = 2.81
C Language Examples