long 不足以存储整数
long not enough to store an integer
public class SDO
{
public static void main(String args[])
{
SDO sdo = new SDO();
System.out.println(sdo.amountOfData(1));
System.out.println(sdo.amountOfData(86400));
}
public long amountOfData(int seconds)
{
long result = (4096*4096*seconds);
return result;
}
}
此代码在我的测试中返回,错误:amountData(1000) expected:<16777216000> but was:<-402653184>。键入 long 不应该存储更大的整数吗?或者,如果不是,如何让这段代码工作?
改变
long result = (4096*4096*seconds);
到
long result = (4096L*4096L*seconds);
为了获得 long
结果并避免 int
溢出。
4096*4096*seconds
是 3 int
的乘积,结果是 int
,它可能会在分配给您的 long
变量之前溢出。
有:
long result = (4096*4096*seconds);
result
确实可以保存值,但是 计算 是专门用 int
类型完成的,因为它只对 int
s.
所以表达式的 结果 将是一个 int
,您稍后会将其放入 long
但 不会在你丢失信息之前。
您可以强制 Java 使用 long
作为 中间 结果,只需将第一个常量设置为 long
:
long result = 4096L * 4096 * seconds;
不过为了让你的意图更清楚,将它们全部设为多头可能更为谨慎。
这包含在 Java 语言规范中:
Numeric promotion is applied to the operands of an arithmetic operator. Numeric promotion contexts allow the use of an identity conversion, a widening primitive conversion, or an unboxing conversion.
Numeric promotions are used to convert the operands of a numeric operator to a common type so that an operation can be performed. The two kinds of numeric promotion are unary numeric promotion and binary numeric promotion.
一个其他解决方案是让函数调用自身扩展数据类型,例如:
public long amountOfData (long seconds) {
return seconds * 4096 * 4096;
}
这将产生类似的效果,因为 seconds
现在将是 long
,因此计算将作为 long
完成。它还会稍微缩短您的代码。
public class SDO
{
public static void main(String args[])
{
SDO sdo = new SDO();
System.out.println(sdo.amountOfData(1));
System.out.println(sdo.amountOfData(86400));
}
public long amountOfData(int seconds)
{
long result = (4096*4096*seconds);
return result;
}
}
此代码在我的测试中返回,错误:amountData(1000) expected:<16777216000> but was:<-402653184>。键入 long 不应该存储更大的整数吗?或者,如果不是,如何让这段代码工作?
改变
long result = (4096*4096*seconds);
到
long result = (4096L*4096L*seconds);
为了获得 long
结果并避免 int
溢出。
4096*4096*seconds
是 3 int
的乘积,结果是 int
,它可能会在分配给您的 long
变量之前溢出。
有:
long result = (4096*4096*seconds);
result
确实可以保存值,但是 计算 是专门用 int
类型完成的,因为它只对 int
s.
所以表达式的 结果 将是一个 int
,您稍后会将其放入 long
但 不会在你丢失信息之前。
您可以强制 Java 使用 long
作为 中间 结果,只需将第一个常量设置为 long
:
long result = 4096L * 4096 * seconds;
不过为了让你的意图更清楚,将它们全部设为多头可能更为谨慎。
这包含在 Java 语言规范中:
Numeric promotion is applied to the operands of an arithmetic operator. Numeric promotion contexts allow the use of an identity conversion, a widening primitive conversion, or an unboxing conversion.
Numeric promotions are used to convert the operands of a numeric operator to a common type so that an operation can be performed. The two kinds of numeric promotion are unary numeric promotion and binary numeric promotion.
一个其他解决方案是让函数调用自身扩展数据类型,例如:
public long amountOfData (long seconds) {
return seconds * 4096 * 4096;
}
这将产生类似的效果,因为 seconds
现在将是 long
,因此计算将作为 long
完成。它还会稍微缩短您的代码。