Java程序用于乘以给定的浮点数


假设有两个浮点数作为操作数,你的任务是编写一个Java程序来乘以给定的数字。要执行此操作,请初始化两个浮点值,相乘并将结果存储在另一个浮点类型变量中。

Float是Java中一种数据类型,用于存储带小数部分的数字。

示例场景

Input 1: num1 = 1.2 Input 2: num2 = 1.4 Output: product = 1.68

使用乘法运算符

乘法运算符由星号(*)表示。它属于Java中的算术运算符。它可以用于乘以运算符两侧的浮点值。

示例

以下是一个Java程序,用于乘以给定的浮点数。

Open Compiler
public class MultiplyFloatingNumbers { public static void main(String args[]){ float flt1 = 12.2f; System.out.println("First floating point number:: " + flt1); float flt2 = 6.3f; System.out.println("Second floating point number:: " + flt2); // multiplying float product = flt1 * flt2; System.out.println("Product of given floating point numbers:: " + product); } }

运行此代码后,您将获得以下结果:

First floating point number:: 12.2
Second floating point number:: 6.3
Product of given floating point numbers:: 76.86

使用BigDecimal精度进行乘法

浮点数运算容易受到舍入误差和精度损失的影响。因此,Java引入了Bigdecimal类,以便我们可以获得精确的精度。

示例

在这个Java程序中,我们使用BigDecimal进行乘法运算以获得精度。

Open Compiler
import java.math.BigDecimal; public class MultiplyFloatingNumbers { public static void main(String[] args) { float flt1 = 2.2f; System.out.println("First floating point number:: " + flt1); float flt2 = 4.3f; System.out.println("Second floating point number:: " + flt2); // Converting float to BigDecimal BigDecimal bd1 = BigDecimal.valueOf(flt1); BigDecimal bd2 = BigDecimal.valueOf(flt2); // Multiplying BigDecimal product = bd1.multiply(bd2); System.out.println("The product is: " + product); } }

上述代码的输出如下:

First floating point number:: 2.2
Second floating point number:: 4.3
The product is: 9.460000624656686494947038590908

Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.

使用用户自定义函数进行乘法

在这种方法中,创建一个用户自定义函数,该函数接受两个浮点数作为参数,并使用乘法运算符查找操作数的乘积。

示例

以下是上述讨论方法的实际演示:

Open Compiler
public class Main { // method to multiply public static float multiplyFloatingNumbers(float f1, float f2) { return f1 * f2; } public static void main(String[] args) { float flt1 = 2.2f; System.out.println("First floating point number:: " + flt1); float flt2 = 4.3f; System.out.println("Second floating point number:: " + flt2); double product = multiplyFloatingNumbers(flt1, flt2); System.out.printf("The product is: %.2f", product); } }

执行此代码后,将产生以下结果:

First floating point number:: 2.2
Second floating point number:: 4.3
The product is: 9.46

更新于:2024年8月16日

1K+ 浏览量

启动您的职业生涯

通过完成课程获得认证

开始学习
广告