这个 While 循环是如何退出的? (java)
How does this While loop exit ? (java)
我试图弄清楚这个程序是如何工作的,但我卡在了 While 循环中,我不明白第二个循环是如何退出的,因为 v
永远不会等于 0 或负数.因为这是退出该循环的唯一条件,还是我错过了更深层次的东西?该代码将整数 (>0) 转换为二进制。
public class Binary {
public static void main(String[] args) {
// read in the command-line argument
int n = Integer.parseInt(args[0]);
// set v to the largest power of two that is <= n
int v = 1;
while (v <= n/2) {
v = v * 2;
}
// check for presence of powers of 2 in n, from largest to smallest
while (v > 0) {
// v is not present in n
if (n < v) {
System.out.print(0);
}
// v is present in n, so remove v from n
else {
System.out.print(1);
n = n - v;
}
// next smallest power of 2
v = v / 2;
}
System.out.println();
}
}
v 是一个 int,在 Java 中 1/2 作为 int 给出 0。你的循环遍历了 2 的所有幂,所以将达到 1,然后达到 0。
运行在调试器里看吧!
考虑从
开始
n=10
所以
v=8
系统会打印
1010
迭代次数为:
1 - 10>8 else 语句所以打印 1 and: n=2, v=4
2 - 2<4 if 语句所以打印 0 and: v=2
3 - 2=2 else 语句所以打印 1 and: n=0, v=1
4 - 0<1 if 语句所以打印 0 并且:n=0, v=1/2 即 0 作为整数
在下一次迭代中,while 条件不再满足,代码结束。
感觉你对整数除法的理解有问题。在整数除法中,3/2
不等于 1.5
而是 1
。所以类似地 1/2
不等于 0.5
而是 0
。由于变量 v
是整数,除以整数 2
始终是整数除法。所以你的变量 v
最终会达到 0
.
我试图弄清楚这个程序是如何工作的,但我卡在了 While 循环中,我不明白第二个循环是如何退出的,因为 v
永远不会等于 0 或负数.因为这是退出该循环的唯一条件,还是我错过了更深层次的东西?该代码将整数 (>0) 转换为二进制。
public class Binary {
public static void main(String[] args) {
// read in the command-line argument
int n = Integer.parseInt(args[0]);
// set v to the largest power of two that is <= n
int v = 1;
while (v <= n/2) {
v = v * 2;
}
// check for presence of powers of 2 in n, from largest to smallest
while (v > 0) {
// v is not present in n
if (n < v) {
System.out.print(0);
}
// v is present in n, so remove v from n
else {
System.out.print(1);
n = n - v;
}
// next smallest power of 2
v = v / 2;
}
System.out.println();
}
}
v 是一个 int,在 Java 中 1/2 作为 int 给出 0。你的循环遍历了 2 的所有幂,所以将达到 1,然后达到 0。
运行在调试器里看吧!
考虑从
开始n=10
所以
v=8
系统会打印
1010
迭代次数为:
1 - 10>8 else 语句所以打印 1 and: n=2, v=4
2 - 2<4 if 语句所以打印 0 and: v=2
3 - 2=2 else 语句所以打印 1 and: n=0, v=1
4 - 0<1 if 语句所以打印 0 并且:n=0, v=1/2 即 0 作为整数
在下一次迭代中,while 条件不再满足,代码结束。
感觉你对整数除法的理解有问题。在整数除法中,3/2
不等于 1.5
而是 1
。所以类似地 1/2
不等于 0.5
而是 0
。由于变量 v
是整数,除以整数 2
始终是整数除法。所以你的变量 v
最终会达到 0
.