日历运行无限循环

calender running infinite loop

本文关键字:无限循环 运行 日历      更新时间:2023-10-16

用于输出日历的代码工作正常,但它没有显示每个月所需的空格数。假设一月在星期五结束,二月应该从星期六开始。

为了保持计数,我添加了一个line变量,每当一个新的月份开始时,通过查看开始日期即sd来给出所需的空格数。

所以在每个月之后,我必须将line初始化为1来为下个月腾出空间,但是将line初始化为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   Sn";
  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.
}

我怀疑变量没有被初始化。正如您所说,这很好,只是使用了不正确的空格

你还没有发布一个MCVE,但一定要声明和初始化你的循环变量,如:

int month = 0;
int line = 0;
int days = 0;
int j = 0;
int i = 0;
int sd = 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++)将在if ((line == 1) && (i < sd))i < sd条件为假之前在i < 7上终止,因为line被卡在1上,i由于for-loop的外部终止条件而永远不会大于6。

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