简体   繁体   English

Sum 在 Kotlin 中给出一个负数

[英]Sum is giving a negative number in Kotlin

So here is my Kotlin Code:所以这是我的 Kotlin 代码:

val intBoth = 1_391_000_000 + 1_432_342_859

println("China plus India: " + intBoth)

And the result is negative:结果是否定的:

China plus India: -1471624437

What went wrong here?这里出了什么问题?

If you you don't select a your variable type (like Long,Float,Bytes,Shorts ), the kotlin asumes it is an Integer .如果您不是 select变量类型(如Long,Float,Bytes,Shorts ),则 kotlin 假定它是ZA0FAEF0851B4294C06F2B94BB1CB2044

The variable types have boundary conditions for representing number values.变量类型具有表示数值的边界条件。

The boundary of Integers are between -2,147,483,648 and 2,147,483,647 (It's about byte of size).整数的边界在 -2,147,483,648 和 2,147,483,647 之间(大约是字节大小)。 The variables of your calculation of summiation are Integer so the complier expect the total value is Integer, but the result is out of the range of Integer variable type.您计算求和的变量是 Integer,所以编译器期望总值是 Integer,但结果超出了 Integer 变量类型的范围。 Yo can overcome the problem by convert to Long your types of elements.你可以通过将元素类型转换为Long来克服这个问题。 Write .toLong end of the variables for converting写入.toLong变量的长尾进行转换

fun main() {
  val intBoth = 1391000000.toLong() + 1432342859.toLong()

println("China plus India: " + intBoth)
          
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM