【问题标题】:Storing the sum of two Ints in a Long in Java [duplicate]在Java中将两个Int的总和存储在一个Long中[重复]
【发布时间】:2015-11-28 23:19:34
【问题描述】:

我要做的基本上是将两个 int 值存储在两个变量中,然后将两个 int 的操作值存储在 long 中。我的代码是:

int operand1 = 2147483647;
int operand2 = 1; 
long longValue = operand1 + operand2;

我遇到的问题是我需要 longValue 也等于 2147483648 而不是 -2147483648 因为它正在环绕它。我需要操作数 1 和 2 都保留为整数。非常感谢任何帮助!

【问题讨论】:

  • 添加时将整数转换为长整数。 long longValue = (long) operand1 + (long) operand2

标签: java int long-integer


【解决方案1】:

将两个整数都转换为长整数。

long longValue = ((long)operand1) + ((long)operand2)

【讨论】:

    【解决方案2】:
    int operand1 = 2147483647;
    int operand2 = 1; 
    long longValue = (long) operand1 + operand2;
    

    只转换第一个操作数 1 就足够了,即使操作数 1 = 1 和操作数 2 = 2147483647,因为 long + int 会自动转换为 long。

    【讨论】:

      【解决方案3】:

      试试看,

      long longValue = new Long(operand1) + new Long(operand2);
      

      【讨论】:

        【解决方案4】:

        正如其他人所说,解决方案是将赋值的 RHS(右侧)上的一个(或两个)操作数转换为 long。当+ 操作数为int 和另一个long 时,JLS 表示程序会将int 操作数转换为long 并使用64 位算术执行操作。

        在您编写的代码中,JLS 表示应该使用 32 位算术添加两个 int 值。 32 位到 64 位的转换随后发生,因为正在分配值。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-03-10
          • 1970-01-01
          • 1970-01-01
          • 2015-05-22
          • 2016-10-25
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多