public class Hello
{
public static void main(String[] args)
{
short value = -8;
short value1 = -3;
short val = 0;
val = value%value1;
System.out.println(val);
}
}
很简单的程序,但是在编译的时候提示“可能损失精度”找到int 需要short val = value%value1;
short存储范围是从-32768到+32767,怎么会超出范围呢?
{
public static void main(String[] args)
{
short value = -8;
short value1 = -3;
short val = 0;
val = value%value1;
System.out.println(val);
}
}
很简单的程序,但是在编译的时候提示“可能损失精度”找到int 需要short val = value%value1;
short存储范围是从-32768到+32767,怎么会超出范围呢?
类型小于int时 都是自转成int的
如 short s = 12;
s = s + 1;就会报错
而 s += 1; 就不报错
比 int 小的类型 计算时候 都是 转成 int 计算的。故计算后结果是 int 的
value%value1 取模之后是int 类型 int类型要转换为short类型,当然得加强制转换啊
一句话,就是高精度转换成低精度会损失精度,用强制类型转换或者用Decinmal这个类来做精度转换问题