为什么在使用 long 数据类型时会出现错误?

huangapple go评论146阅读模式
英文:

Can anyone tell me why it is giving error, while using long datatype

问题

long x = sc.nextLong();
if (x < 9223372036854775807L && x > -9223372036854775808L) 
{
System.out.println("* long");
}
英文:
long x = sc.nextLong();
if (x &lt; 9223372036854775807 &amp;&amp; x &gt; -9223372036854775808) 
{
System.out.println(&quot;* long&quot;);
}

It's having error at if() condition line

>The literal 9223372036854775807 of type int is out of range

Can anyone tell me how to reslove it?

答案1

得分: 1

long x = sc.nextLong();

if (x < 9223372036854775807L && x > -9223372036854775808L) {
    System.out.println("* long");
}

要指定一个数字字面量为 long 而不是 int,在字面量的末尾添加一个 "L"(表示 long)。如果末尾没有 "L",编译器会将这些数字识别为整数,并且在 if 语句中指定的整数超出了整数的范围。


<details>
<summary>英文:</summary>

long x = sc.nextLong();

if (x < 9223372036854775807L && x > -9223372036854775808L) {
System.out.println("* long");
}


To specify a numeric&#160;literal&#160;as a&#160;long&#160;instead of an int , add an L (for&#160;long) to the end of the&#160;literal. Without &quot;L&quot; in the end, the compiler is identifying the numbers as integers and the specified integers in the if statement are out of bounds of an Integer.

</details>



huangapple
  • 本文由 发表于 2020年7月22日 23:23:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/63037736.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定