[英]Casting primitive data types
public class TestEmployee {
public static void main(String args[]) {
byte b=(byte)1*200;
System.out.println(b);
}
}
我已经写了上面的简单代码。 但我收到以下错误“可能失去精度”
据我所知,当我们执行 integer 计算时,操作数被转换为 int 然后执行计算。 最终结果是 int。 现在由于字节数据类型的范围是(-128 到 127),上述计算超出了字节范围。 所以我将其转换为字节。 那为什么我会收到错误消息。
请帮助和纠正我的铸造概念..
您将1
转换为一个字节,而不是1*200
的结果。 所以你想使用
byte b = (byte)(1*200);
在这种情况下。
您的代码应该像这样 go ......只是在乘法运算之前缺少括号,否则只有 1 将被向下转换,200 仍然为 integer
public class TestEmployee {
public static void main(String args[])
{ byte b=(byte) ( 1 * 200);
System.out.println(b);
}
}
您在向下转换时缺少括号()
。
改成这样,
byte b=(byte)(1*200);
这样写的时候
byte b=(byte)1*200;
^
`compilation error : possible loss of precision`
这是因为它试图将int: 200
转换为 byte ,这将导致编译错误。
你没有把1 * 200
放在括号里。 它应该是byte b = (byte)(1 * 200).
否则你做byte b = 200
这是一个 int 并且你得到一个错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.