<分区>
我一直在想这个问题,当我尝试执行以下操作时,c 和 java 都有不同的输出
在 C 中:
int i=5;
while(i--)
{
printf(i);
}
output: 54321
和java
int i=5;
while(i--) // Compilation error
{
System.out.println(i);
}
为什么? while条件下出现编译错误
<分区>
我一直在想这个问题,当我尝试执行以下操作时,c 和 java 都有不同的输出
在 C 中:
int i=5;
while(i--)
{
printf(i);
}
output: 54321
和java
int i=5;
while(i--) // Compilation error
{
System.out.println(i);
}
为什么? while条件下出现编译错误
最佳答案
在 Java 中,整数类型(int、long 等)和 boolean 类型是分开的。因此,在需要 boolean 值的地方不能使用返回 int 的表达式。
因此Java中的条件必须是:
while (i-- > 0)
在 C 中,一个等于 0 的 int 可以被视为 false,这就是为什么 while (i--)
是有效的。
附言我假设 Java 代码中缺少 i
的初始化是一个遗漏。
关于java - 为什么 while 循环在 java 和 c 中的工作方式不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36467523/