问题描述
我需要将a=n×s^2
转换为Java。我的代码看起来像这样:
public float ABC( float n,float s)
{
a = n*s;
return a*a;
}
但是,如果我将其打印出来,它将返回以下错误:
This method must return a result of type float
因此,我认为我的解决方案不正确。谁能提供任何解决方案?我是Java的新手。
解决方法
您应该声明变量a
的类型:
public static float ABC( float n,float s) {
float a = n * s;
return a * a;
}
,
您需要声明a
的类型,并且由于您没有使用任何实例变量,因此可以使方法static
。
此外,您可以将结果传递到Math.pow
并将结果double
投射到float
。
public class Question64613567 {
public static void main(String[] args) {
System.out.println(abc(2,3)); // 36.0
System.out.println(abc2(2,3)); // 36.0
}
public static float abc(float n,float s) {
float a = n * s;
return a * a;
}
public static float abc2(float n,float s) {
return (float) Math.pow(n * s,2);
}
}