有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java一个整数可以和一个长整数相加吗?

我为这样一个蹩脚的问题感到抱歉。我会亲自测试这个。。。但不幸的是,我不知道如何为java编写代码,仅仅回答这一个问题是不值得的

是否可以将long和整数相加? 我的朋友正在做一个项目,我认为他可以通过使用long而不是整数来纠正他的一个错误。(他希望数字高于21.47亿)

我试着自己做了一点研究,我很惊讶答案不那么容易找到。这是我能够找到的信息来源之一

如果其中一个或两个整数类型都是long,则结果是long https://community.oracle.com/message/5270213

对吗?再一次,很抱歉,我无法亲自测试


共 (3) 个答案

  1. # 1 楼答案

    是的,你可以添加一个long和一个int就可以了,最后你会得到一个long

    正如Java语言规范中所描述的那样,int经历了更广泛的原语转换,特别是JLS8, §5.1.2

    JLS8 §5.6.2是详细描述这里发生的事情的重要部分(我的粗体):

    Widening primitive conversion (§5.1.2) is applied to convert either or both operands as specified by the following rules:

    If either operand is of type double, the other is converted to double.

    Otherwise, if either operand is of type float, the other is converted to float.

    Otherwise, if either operand is of type long, the other is converted to long.

    Otherwise, both operands are converted to type int.

  2. # 2 楼答案

    你总是可以尝试这样的事情。例如使用jdoodle

    正如你所见,这是完全可能的。建议使用long来存储结果,但不是必需的。在后一种情况下,如果出现溢出,Java将只使用32个最低有效位,因此:

    6666555555555544444444443333333333222222222211111111110000000000 (index)
    3210987654321098765432109876543210987654321098765432109876543210
                                    
    0101010101010010000011110010101111101010101111101011101011011101 (value)
    

    将存储为:

    33222222222211111111110000000000 (index)
    10987654321098765432109876543210
                    
    11101010101111101011101011011101 (value)
    
  3. # 3 楼答案

    是的,你可以把一个长的和一个整数相加。在java中有几种基本数据类型intlong变量是其中的两个。这两种数据类型用于存储整数值。区别在于变量的大小

    int:32位

    long:64位

    可以将int和long加在一起,当jvm添加这两个变量时,结果将生成一个long值。所以你必须使用一个长变量来存储答案。这是由于java的自动类型转换

    如果你想得到int值作为答案,你必须把cast中的长值int

        int x=5;  //int value
        long y = 10;  //long value
        long z = x + y;  //result is a long value(normally jvm does)
        int i=(int) (x+y);  // result is cast into a int value.
    

    z和i都得到值:15