【问题标题】:While statement with multiple conditions具有多个条件的 while 语句
【发布时间】:2016-02-20 08:02:52
【问题描述】:

我有以下 while 语句 -

while ((!testString.Contains("hello")) && (NewCount != OldCount) && (attemptCount < 100))
{
    //do stuff (steps out too early)
}

即使所有条件都没有满足,这也是退出语句。

我试图减少它 -

while (!testString.Contains("hello"))
{
    // this works and steps out when it should
}

例如,当出现hello 时,它就会退出。我还尝试将其更改为 OR 语句,该语句将问题反转为永远不会退出该语句。

添加&amp;&amp; (NewCount != OldCount) &amp;&amp; (attemptCount &lt; 100)) 条件导致此行为我该如何解决?

【问题讨论】:

  • NewCountOldCountattemptCount的值是多少?
  • 我认为您需要为此提供更多上下文。

标签: c# while-loop conditional-statements


【解决方案1】:

即使所有条件都超出了该语句 没有遇到过。

要实现这一点,您需要指定逻辑 OR (||)。 例如:

while ((!testString.Contains("hello")) || (NewCount != OldCount) || (attemptCount < 100))
{
    //while at least one those conditions is true, loop will work
}

这意味着你需要在循环内部引入安全检查,在需要的地方,对于不太正确的条件,while 循环仍在执行。

【讨论】:

    【解决方案2】:

    作为对 Tigra 的回答的补充。通常(为了避免与复杂条件混淆)将条件推入循环可能很有用:

      while (true) { // loop forever unless:
        if (testString.Contains("hello")) // ...test string contains "hello"
          break;
    
        if (NewCount == OldCount) // ...counts are equal
          break;
    
        if (attemptCount >= 100) // ... too many attempts
          break;
    
        // ...it's easy to add conditions (as well as comment them out)  when you have them
    
        // Loop body
      }
    

    【讨论】:

      猜你喜欢
      • 2014-10-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-28
      • 2014-01-09
      • 2021-12-19
      • 2023-03-31
      • 2020-12-13
      相关资源
      最近更新 更多