java 中Math.sqrt()使用注意事项 Type mismatch: cannot convert from double to float

来源:互联网 发布:什么是淘宝的企业店铺 编辑:程序博客网 时间:2024/06/11 20:54

若使用Math.sqrt() 出现Type mismatch: cannot convert from double to float

那是因为Math.sqrt()返回正确舍入的一个double值的正平方根,若你将值赋值给不是double类型的变量,将会出现以上问题。


例子: 

public class Main {
public static void main(String[] args) {
float[] a = newfloat[6];
float[] s = newfloat[3];
System.out.println("Enter three points for a triangle:");
Scanner tri = new Scanner(System.in);
for(int i=0; i<6; i++) {
a[i] = tri.nextFloat();
}
s[0] = Math.sqrt(Math.pow(Math.abs(a[0]-a[2]), 2)+Math.pow(Math.abs(a[1]-a[3]), 2));
s[1] = Math.sqrt(Math.pow(Math.abs(a[0]-a[4]), 2)+Math.pow(Math.abs(a[1]-a[5]), 2));
s[2] = Math.sqrt(Math.pow(Math.abs(a[2]-a[4]), 2)+Math.pow(Math.abs(a[3]-a[5]), 2));
System.out.println(s[0]);
System.out.println(s[1]);
System.out.println(s[2]);
}
}

这个将会出错,因为接受Math.sqrt返回值的变量是float变量


正确的是

public class Main {
public static void main(String[] args) {
double[] a = newdouble[6];
double[] s = newdouble[3];
System.out.println("Enter three points for a triangle:");
Scanner tri = new Scanner(System.in);
for(int i=0; i<6; i++) {
a[i] = tri.nextFloat();
}
s[0] = Math.sqrt(Math.pow(Math.abs(a[0]-a[2]), 2)+Math.pow(Math.abs(a[1]-a[3]), 2));
s[1] = Math.sqrt(Math.pow(Math.abs(a[0]-a[4]), 2)+Math.pow(Math.abs(a[1]-a[5]), 2));
s[2] = Math.sqrt(Math.pow(Math.abs(a[2]-a[4]), 2)+Math.pow(Math.abs(a[3]-a[5]), 2));
System.out.println(s[0]);
System.out.println(s[1]);
System.out.println(s[2]);
}
}

阅读全文
0 0