int到long赋值 [英] int to long assignment

查看:642
本文介绍了int到long赋值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试这个int和long转换,我尝试将 int 变量分配给 long 变量。代码如下:

I have been trying this int and long conversion where I have tried assigning an int variable to a long variable. The code is as follows:

public static void main(String []args){
    int i = 1024;
    long j = i;
    long k = i*i*i*i;
    System.out.println("j= " +j+ ", k= " +k);
}

因此,在打印 j ,它只输出 1024 。但是在打印 k 时,它显示溢出( k = 0)。我通过使用这种技术解决了这个问题,我已经明确地将每个 i 转换为 long 。即。

So, while printing j, it simply gave an output of 1024. But while printing k, it showed an overflow (k=0). I sorted out this problem by using this technique, where I have explicitly casted each i to long. i.e.

public static void main(String []args){
    int i = 1024;
    long j = i;
    long k = ((long)i)*((long)i)*((long)i)*((long)i);
    System.out.println("j= " +j+ ", k= " +k);
}

现在,它显示了两个 j <的正确值/ code>和 k
所以,我想知道为什么需要在第二种情况下转换 int 而不是在第一种情况下。 k ,作为 long ,可以在此繁重的作业后保留此值。但是,为什么没有正确分配?

Now, it showed correct values of both j and k. So, I wanted to know why is this needed to cast int in the second case but not in the first one. k, being a long can retain this value after this heavy assignment. But, why it is not been correctly assigned?

推荐答案

原因是你的行

long k = i*i*i*i;

可以被认为是

long k = ((i*i)*i)*i;

或...

int k1 = i*i;
int k2 = k1*i;
int k3 = k2*i;
long k = k3;

因此当任何 kn 溢出时,你得到错误。

So when any of kn overflows, you get the error.

当你进行演员表演时,你总是将 long 放在一起,从而避免这个问题。 。

When you do your casts you're obviously circumventing this problem by always multiplying longs together.

当然,对初始程序的最简单修改是将 i 定义为很长而不是 int

Of course the simplest modification to your initial program is to define i as a long straight away, instead of an int.

long i = 1024L;

这篇关于int到long赋值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆