日历运行无限循环

时间:2014-07-29 06:50:46

标签: c++ controls infinite-loop

输出日历的代码工作正常,但它并未显示每个月所需的空格数。假设1月在星期五结束,2月应从星期六开始。

为了统计我已经添加了一个line变量,每当新月开始时,通过查看开始日sd来提供所需的空格数。

所以在每个月之后我必须将line初始化为1以便为下个月腾出空间,但是将行初始化为1正在运行无限循环。

while (month <= 12)
{
  if (month == 2)
    days = 28;

  else if (month == 4 || month == 6 || month == 9 || month == 11)
    days = 30;

  else days = 31;

  cout << endl << endl << endl;

  if (month == 1)
    cout << "      JANUARY 20XX    \n";

  else if (month == 2)
    cout << "      FEBRUARY 20XX    \n";

  else if (month == 3)
    cout << "      MARCH 20XX    \n";

  else if (month == 4)
    cout << "      APRIL 20XX    \n";

  else if (month == 5)
    cout << "      MAY 20XX    \n";

  else if (month == 6)
    cout << "      JUNE 20XX    \n";

  else if (month == 7)
    cout << "      JULY 20XX    \n";

  else if (month == 8)
    cout << "      AUGUST 20XX    \n";

  else if (month == 9)
    cout << "      SEPTEMBER 20XX    \n";

  else if (month == 10)
    cout << "      OCTOBER 20XX    \n";

  else if (month == 11)
    cout << "      NOV 20XX    \n";

  else if (month == 12)
    cout << "      DEC 20XX    \n";

  cout << "-   -   -   -   -   -   -\n";
  cout << "M   T   W   T   F   S   S\n";
  cout << "-   -   -   -   -   -   -\n";

  while (j < days) {
    for (i = 0; i < 7
         && j <= days; i++) { //i from 0to 6 for 7 days.j from 1 to no. of
      //days in the month
      if ((line == 1) && (i < sd))     //line =1 so that space is only in first line
        cout << "    ";

      else {
        cout << j << "  ";
        j++;

        if (i == 6) {
          cout << endl;
          line++;
        }
      }
    }
  }

  if (i == 7)
    sd = 1;

  else sd = i + 1;

  cout << sd;
  month++;
  j = 1;
  i = 0;
  line = 1; //infinite loop here!On removing line=1, it works fine except spaces.
}

2 个答案:

答案 0 :(得分:1)

我怀疑变量没有被初始化。 This works fine, as you say, just with the incorrect spaces

您还没有发布MCVE,但请务必声明并初始化您的循环变量,例如:

int month = 0;
int line = 0;
int days = 0;
int j = 0;
int i = 0;
int sd = 0;

答案 1 :(得分:0)

在下面的代码摘录中:

while (j < days) {
for (i = 0; i < 7 && j <= days; i++) { 
  if ((line == 1) && (i < sd))     
    // The above if statement is false if 'line != 1' or 'i >= sd'.
  else {
    // 'line' is incremented in here. Hence this code will only be
    // executed if the preceding if-statement is terminated via the 'i < sd' condition.
  }

我怀疑i永远不会成为>= sdsd的价值是什么?

如果sd大于或等于7,则表示您遇到问题。

for (i = 0; i < 7 && j <= days; i++)将在i < 7 i < sd之前if ((line == 1) && (i < sd))的{​​{1}}条件终止,因为line卡在1上且{由于外部i终止条件,{1}}永远不会超过6。

for-loop将保持为真,因为永远不会执行递增j <= days的代码。