Using Math.pow in Java – 在Java中使用Math.pow

最后修改: 2017年 3月 25日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

The power of a number means how many times to use the number in multiplication. This can be easily calculated in Java.

一个数字的幂意味着在乘法中使用该数字的多少倍。这在Java中可以很容易地计算出来。

2. Math.pow Example

2.Math.pow 例子

Before looking at the example, let’s look at the method’s signature:

在看这个例子之前,我们先看一下这个方法的签名。

public double pow(double a, double b)

The method raises a to the power of b and returns the result as double. In other words, a is multiplied by itself b times.

该方法将a提高到b的幂,并将结果返回为double。换句话说,a被自己乘以b倍。

Let’s look at a simple example now:

现在让我们看一个简单的例子。

int intResult = (int) Math.pow(2, 3);

The output will be 8. Please note that the int casting in the above example is required if we want to have an Integer result.

输出结果将是8。请注意,如果我们想得到一个Integer的结果,上述例子中的int转换是必需的

Let’s now pass a double as an argument and see the results:

现在让我们传递一个double作为参数,看看结果。

double dblResult = Math.pow(4.2, 3);

The output will be 74.08800000000001.

输出结果将是74.08800000000001。

Here we’re not casting the result to an int as we are interested in a double value. Since we have a double value, we can easily configure and use a DecimalFormat to round the value to two decimal places, resulting in 74.09:

在这里,我们没有将结果转换成int,因为我们对double值感兴趣。由于我们有一个double值,我们可以很容易地配置并使用DecimalFormat来将该值四舍五入到小数点后两位,结果是74.09。

DecimalFormat df = new DecimalFormat(".00");
double dblResult = Math.pow(4.2, 3);

3. Conclusion

3.结论

In this quick article, we have seen how to use the Java’s Math.pow() method to calculate the power of any given base.

在这篇文章中,我们看到了如何使用Java的Math.pow()方法来计算任何指定基数的幂。

Like always, the full source code is available over on GitHub.

像往常一样,完整的源代码可以在GitHub上找到