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]);
}
}
- java 中Math.sqrt()使用注意事项 Type mismatch: cannot convert from double to float
- junit Type mismatch: cannot convert from Test to Annotation
- Type mismatch: cannot convert from Test to Annotation
- Id Type mismatch: cannot convert from connection to connection
- Type mismatch: cannot convert from Object to String
- Type mismatch: cannot convert from Enumeration<String> to Enumeration<Object>
- Type mismatch: cannot convert from MainFragment to Fragment 报错
- Type mismatch: cannot convert from MainFragment to Fragment 报错
- Type mismatch: cannot convert from CharFragment to Fragment错误
- Type mismatch: cannot convert from Test to Annotation
- Type mismatch: cannot convert from Object to String
- Type mismatch: cannot convert from MainFragment to Fragment 报错
- Type mismatch: cannot convert from Test to Annotation
- Hibernate Type mismatch: cannot convert from CascadeType to CascadeType[]
- Type mismatch: cannot convert from Test to Annotation
- 解决Type mismatch: cannot convert from ByteMatrix to BitMatrix
- 关于 Type mismatch: cannot convert from Integer to int
- Type mismatch: cannot convert from ComboPooledDataSource to DataSource
- Java面试题全集(4)
- 01-复杂度1 最大子列和问题
- SQL Server之选出某个字段中全部为数字或全部为字母的记录
- 2017 乌鲁木齐赛区网络赛 Half-consecutive Numbers(【规律题】)
- 跳台阶(剑指Offer 第 8 题)
- java 中Math.sqrt()使用注意事项 Type mismatch: cannot convert from double to float
- 交换排序(冒泡排序--快速排序)
- supervisord上手与配置
- LeetCode刷题(5)
- solr安装配置
- 圆的面积和周长
- C语言习题三
- 2.1.5脏读(dirtyRead)
- Java基础学习之java基本语法(4)【数组】