常见用法
pow 是静态方法,要用类名 Math 来访问该方法,如下:
Math.pow(底数a,指数b)
表示 a 的 b 次方,返回类型为 double
应用:用 Math.pow() 实现数组的交错求和
public static void main(String[] args) {
int n = 0;
int a = 0;
int[] b = {1,2,3,4,5,6,7,8,9};
for (int i = 0; i < b.length; i++) {
a += b[i] * Math.pow(-1,n);
n++;
}
System.out.println(a);
}
结果:输出 5
说明:用 Math.pow 求 -1 的次方,奇次幂为负数,偶次幂为正数,这样即可实现数组交错求和
常见错误
1、如果底数 a 为负数并且指数 b 不是整数,就会返回 NaN
public static void main(String[] args) {
double a = Math.pow(-1,1.2);
System.out.println(a);
}
结果:NaN
2、如果底数 a 是 0,指数 b 是负数,返回 Infinity (无穷)。
public static void main(String[] args) {
double a = Math.pow(0,-1);
System.out.println(a);
}
3、如果返回值超过接收类型的上限,返回 Infinity (无穷)。
public static void main(String[] args) {
double a = Math.pow(10,309);
System.out.println(a);
}
tip:
1、当指数为 -1 时,就是求 1/x
2、当指数为正零或负零,返回 1.0z
3、当指数为 0.5(1/2) 时,相当于求根号 x
原文链接:Java 中 Math.pow 的用法
© 版权声明
THE END


![表情[baoquan]-拾光赋](https://blogs.ink/wp-content/themes/zibll/img/smilies/baoquan.gif)


暂无评论内容