2 回答

TA贡献1775条经验 获得超11个赞
“不兼容类型:可能从 <type1>
到 <type2>
"
<type1>
<type2>
byte
, char
, short
, int
, long
, float
double
.
<type1>
<type2>
int squareRoot = Math.sqrt(i);
sqrt
double
double
int
“潜在损失”是什么意思?
a转换为a long
转到 int
是潜在的有损转换,因为 long
值,这些值没有对应的 int
价值。例如,任何 long
大于2^31-1的值太大,不能将其表示为 int
..同样,任何小于-2^31的数字都太小了。 转换 int
转到 long
不是有损转换,因为 int
值具有相应的 long
价值。 a转换为a float
转到 long
是潜在的有损转换,因为 float
值太大或太小,不能表示为 long
价值。 转换 long
转到 float
不是有损转换,因为 long
值具有相应的 float
价值。(转换值可能不太精确,但“价值”并不意味着.在这方面)
short
到 byte
或 char
char
到 byte
或 short
int
到 byte
,short
或 char
long
到 byte
,short
,char
或 int
float
到 byte
,short
,char
,int
或 long
double
到 byte
,short
,char
,int
,long
或 float
.
如何纠正错误?
int i = 47; int squareRoot = Math.sqrt(i); // compilation error!
int i = 47; int squareRoot = (int) Math.sqrt(i); // no compilation error
47
6.8556546004
squareRoot
6
byte b = (int) 512;
b
0
512
这是因为您在代码中犯了其他错误吗? 如果 <type1>
是一种不同的类型,这样这里就不需要有损耗的转换了吗? 如果必须进行转换,则 沉默
类型转换会做正确的行为吗? 或者您的代码是否应该通过抛出异常来进行范围检查并处理不正确/意外的值?
订阅时“可能的有损转换”。
for (double d = 0; d < 10.0; d += 1.0) { System.out.println(array[d]); // <<-- possible lossy conversion}
int
d
double
int
for (long l = 0; l < 10; l++) { System.out.println(array[l]); // <<-- possible lossy conversion}
带有文字的“可能的有损转换”
21
int
byte
short
int
byte
.
int
byte
.
21
byte
.
to a
,
or
if:
- the value is the result of a compile time *constant expression* (which includes literals), and
- the type of the expression is
,
,
or
.class
添加回答
举报