英文:
Why is casting to int giving me 8 instead of 0?
问题
抱歉,这可能很简单。这已经困扰了我一段时间了。在下面的代码中:
public class Main {
public static void main(String[] args) {
long a = 10000000000L;
System.out.println(a % 10);
}
}
我得到了一个输出为 0,这正是我预期的结果。但是当我像这样转换为 int:
public class Main {
public static void main(String[] args) {
long a = 10000000000L;
System.out.println((int)a % 10);
}
}
我得到了输出 8,而不是预期的 0。我不明白发生了什么。为什么在强制转换后,0 变成了 8?
英文:
Sorry if this is simple. This has been confusing me for some time now. In the following code:
public class Main {
public static void main(String[] args) {
long a = 10000000000L;
System.out.println(a % 10);
}
}
I get an output of 0 which is what I expected. But when I cast to int like this,
public class Main {
public static void main(String[] args) {
long a = 10000000000L;
System.out.println((int)a % 10);
}
}
I get 8 as output instead of 0. I do not understand what is happening. Why is 0 turning into 8 after casting?
答案1
得分: 3
因为首先将变量 a
的值转换为整型,然后再进行取模运算。
你想要的操作是:
public class Main {
public static void main(String[] args) {
long a = 10000000000L;
System.out.println((int)(a % 10));
}
}
英文:
That happens because first is casting the value of a
to int and then doing the module.
What you want to do is:
public class Main {
public static void main(String[] args) {
long a = 10000000000L;
System.out.println((int)(a % 10));
}
}
答案2
得分: 3
由于您将long
转换为int
。而long
的值超出了int
的范围*(-2,147,483,648 到 2,147,483,647)。因此,当您尝试将其转换并存储在int
数据类型中时,JVM会将其简单地舍入到int
数据类型的范围内。存储在int
中的值为1410065408*。
现在,如果您执行1410065408 % 10 = 8。
您可以尝试下面的程序来验证:
public class Test {
public static void main(String[] args) {
long a = 10000000000L;
int b = (int) a;
System.out.println(b); // 这里将会打印 1410065408
System.out.println(b % 10); // 所以这里是 8
}
}
英文:
As you are casting the long
into int
. And the value of long
is beyond the range of int
(-2,147,483,648 to 2,147,483,647). So when you try to cast it and store it in int
data type than the JVM will simply round it of into the range of int
data type. And the value which will be stored in int
is 1410065408.
Now if you do the 1410065408 % 10 = 8.
You can try below program to verify the same.
public class Test {
public static void main(String[] args) {
long a = 10000000000L;
int b = (int) a;
System.out.println(b); // here it will print 1410065408
System.out.println(b % 10); //so here it's 8
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论