为什么强制转换为整型后得到的是 8 而不是 0?

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

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
	}
}

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

发表评论

匿名网友

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

确定