在Java中使用pow()方法
我正在用Java编写一个程序,其中用户应该输入一个整数n。然后,我的程序应该创建一个数组,其中的条目是[1.25^0]、[1.25^1]、。,[1.25^n]。为了实现这一点,我尝试使用pow()方法。我创建数组的代码如下所示:
for (int i = 0; i < n; i++) {
functionG[i] = pow(1.25, n); }
然而,这给了我一条错误消息:“类型函数的方法pow(double,int)未被识别”(函数是我的类的名称)
有人知道我怎么解决这个问题吗?我很确定我的思路是正确的,我只需要让方法正常工作
任何帮助都将不胜感激
# 1 楼答案
使用Math.pow(double, double),或静态导入
pow
,如下所示:# 2 楼答案
当然,您只需要调用} 类中的静态方法:
Math.pow(...)
,因为它是^{注意,我已将其更改为使用
i
而不是n
作为第二个参数您还可以使用以下方法编译原始代码:
在代码顶部的导入语句中。请参阅Java语言规范section 7.5.3,了解其工作原理的详细信息
# 3 楼答案
这是因为pow是Math(java.lang.Math)类中的静态方法。你必须使用数学。而是战俘
# 4 楼答案
我提出的解决方案可能会帮助你更清楚地理解一些事情
# 5 楼答案
正如其他人所指出的,通过导入数学,您可以解决这个问题。pow或明确地称之为pow。然而,鉴于你总是使用整数作为你的幂,数学。与直接乘法相比,pow()是一个相当昂贵的调用。我建议这样一种方法。它可能会给你稍微不同的结果,但它应该是足够的