简体   繁体   English

Java while循环打印平方数不能使用int吗?

[英]Java while loop printing squared numbers can't use int?

In Java, create a do-while loop that starts at 2, and displays the number squared on each line while the number is less than 1,000,000. 在Java中,创建一个从2开始的do-while循环,并在数字小于1,000,000时在每行上显示平方数。 And this is what I have: 这就是我所拥有的:

int k = 2;
do {
    System.out.println(k);
    k *= k;
} while(k < 1000000);

The problem is the output, somehow it is getting stuck at 0 and infinitely looping through 0 to print those out? 问题是输出,以某种方式它卡在0并无限循环通过0来打印输出吗? I don't believe it is due to the fact that the number is out of int range, since a 32 bit number's range is around +/- 2 billion... But when I switch up the data type of k to be long everything works fine... Why is this? 我不相信这是由于数字超出了整数范围,因为32位数字的范围大约是+/- 20亿...但是当我将k的数据类型切换为long时,效果很好...为什么呢?

It really is due to int . 确实是由于int The sequence produced this way is 这样产生的顺序是

2
4
16
256
65536
0

And then it remains zero. 然后它保持为零。 Note that it never rises above 1000000. 请注意,它永远不会升至1000000以上。

With a long , the number after 65536 would be 4294967296 (which does not fit in an int , but does fit in a long ), so it stops. 如果使用long ,则65536之后的数字将是4294967296(不适合int ,但适合long ),因此它停止了。

This is perhaps more obvious in hexadecimal, the sequence then reads (with sufficiently long integers) 这在十六进制中可能更明显,然后读取序列(具有足够长的整数)

2
4
0x10
0x100
0x10000
0x100000000

An int can only keep the lowest 8 hexadecimal digits, so 0x100000000 becomes 0. 一个int只能保留最低的8个十六进制数字,因此0x100000000变为0。

如果要查找2的幂,则需要用k+=1替换k*=k ,并用print(k*k)替换print(k)以2为底的幂运算比二次幂增长快得多,这导致平方超出范围。

Your code to print squares should be 您的打印方格代码应为

int k = 2;
do {
    System.out.println(k*k);
    k++;
}while(k < 1000000);

As you are storing the result in same variable, your output is growing exponentially 当您将结果存储在同一个变量中时,您的输出呈指数增长

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

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