【问题标题】:While and for equivalentwhile 和 for 等价
【发布时间】:2018-04-28 15:37:20
【问题描述】:

请告诉我是否有另一种显示循环不等价的方法

for(int i = 0; i < 10; i++){    
    if (i % 2 == 0)    
            continue;    
    System.out.println(i);    
}

//non equivalent statement. is there any like this(without continue)   
int i = 0;    
while(i < 10){    
    if (i % 2 == 0)    
            continue;    
    System.out.println(i);
}

【问题讨论】:

  • 我不明白你的问题。当然,您的第二个版本不等于第一个版本,因为 i 从不递增。
  • @Reinhard 即使那里有增量(我忘记了)也不等价。我试图证明 while 和 for 循环是不等价的,如果有另一个这样的循环是想要的。
  • 如果您忘记了声明,请编辑您的问题。

标签: java loops for-loop while-loop equivalent


【解决方案1】:

根据我从您那里收集到的代码,您只想在循环中显示奇数。试试这个

for(int i = 0; i < 10; i++){    
    if (i % 2 != 0)    
        System.out.println(i);    
}

与其查找 i 何时为偶数并执行 continue 语句,不如简单地“反转”条件。这段时间也是如此

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-22
    • 1970-01-01
    • 2013-08-19
    • 2021-12-21
    • 2016-04-23
    • 2013-01-31
    • 2015-08-04
    • 1970-01-01
    相关资源
    最近更新 更多