Java 字节的精度可能会降低
我的代码是Java 字节的精度可能会降低,java,Java,我的代码是 class Bauua { public static void main(String...args) { byte a = 10; byte b = 20; byte c = a+b; System.out.println(c); } } 编译时,我得到以下错误 error: possible loss of precision byte c= a+b; required: byte found: int
class Bauua {
public static void main(String...args) {
byte a = 10; byte b = 20;
byte c = a+b;
System.out.println(c);
}
}
编译时,我得到以下错误
error: possible loss of precision
byte c= a+b;
required: byte
found: int
但是当我使用
byte c=(byte)(a+b)代码>代替字节c=a+b代码>它正在成功编译,所以我的问题是,当所有3个变量(即a、b和c)都是字节数据类型时,为什么我需要强制转换它?字节c=a+b
,这里的+
操作符将返回一个int
,这就是为什么需要使用强制转换