我的while循环条件代码有什么问题?

时间:2014-03-07 14:56:19

标签: c++

我编写了以下代码,但是在编译它并运行它之后,没有任何反应。我无法弄清楚它有什么问题。

有两个"和条件"在while循环中。当我取出1个条件时,它工作正常,但是当我把两个条件都放进去时,它就不再有效了。

#include <iostream>
using namespace std;

int main() {
  int n;
  cout << "Enter an integer greater than 10: ";
  cin >> n;

  int c=1;

  while ( (c*5 <= n*2) && (c*5 >= n) ) {
    cout << c*5 << endl;
    c = c+1;
  }

  return 0;
}

2 个答案:

答案 0 :(得分:6)

你的情况永远不会成真。您从n > 10开始,假设为n == 11。最初是c == 1

你的条件是:

while ( (c*5 <= n*2) && (c*5 >= n) )

这样:

while ( (1*5 <= 11*2) && (1*5 >= 11) )

while ( (5 <= 22) && (5 >= 11) )

5小于11,因此5 >= 11为false,循环永远不会运行。

答案 1 :(得分:1)

如果n大于10,那么c*5(即5)将不会是>=n,因此循环条件将为{{1}在第一次评估时。

相关问题