在Java中,我试图将一个int转换为双精度,然后再返回一个int。
我收到此错误:
unexpected type
(double)(result) = Math.pow((double)(operand1),(double)(operand2));
^
required: variable
found: value
从此代码:
(double)(result) = Math.pow((double)(operand1),(double)(operand2));
return (int)(result);
错误消息是什么意思?
你不需要为了调用 Math.pow 而将 int 转换为双精度:
package test;
public class CastingTest {
public static int exponent(int base, int power){
return ((Double)Math.pow(base,power)).intValue();
}
public static void main(String[] arg){
System.out.println(exponent(5,3));
}
}
该消息仅表示您弄乱了语法。 强制转换需要位于相等变量的右侧,而不是要分配给的变量的前面。
Java 中的这段代码:
double my_double = 5;
(double)(result) = my_double;
将抛出编译时错误:
The left-hand side of an assignment must be a variable
不允许对要分配到的等号左侧的变量进行强制转换。 代码的含义甚至没有意义。 您是否试图提醒编译器您的变量是双精度值? 好像还不知道?
您可能打算:
double result = Math.pow((double)(operand1),(double)(operand2));
return (int)(result);
或等效但更简单:
double result = Math.pow((double)operand1,(double)operand2);
return (int)result;
甚至:
return (int)Math.pow((double)operand1,(double)operand2);
假设result
实际上是一个double
,那么你只需要做...
result = Math.pow((double)(operand1),(double)(operand2));
现在,让我们假设result
实际上是int
,那么你只需要做...
result = (int)Math.pow((double)(operand1),(double)(operand2));
更新
根据Patricia Shanahan的反馈,代码中有很多不必要的噪音。 如果没有进一步的上下文,很难完全评论,但是,不太可能(也没有帮助)operand1
和operand2
明确地double
。 Java能够自己解决这个问题。
Math.pow(operand1, operand2);