简体   繁体   English

cout <

[英]cout<<variable; prints out blank

why does the variable "calcDayInt" print out to be blank when the difference between desDateYear & todayDateYear is anything more than 5?(c++) 当desDateYear和todayDateYear之间的差大于5时,为什么变量“ calcDayInt”打印为空白?(C ++)

As long as the variables have a difference of 5 or less the code works alright and gives me the correct answer, but as soon as I increase the difference in the condition in the first for loop and make it >5 the variable gives me an empty output. 只要变量之间的差小于或等于5,代码就可以正常工作并为我提供正确的答案,但是只要我增加了第一个for循环中条件的差并使其大于5,变量就会给我一个空输出。

I tried changing everything and ran through the code manually on a piece of paper, but i cant seem to make it work. 我尝试更改所有内容,并在一张纸上手动运行了代码,但是我似乎无法使其正常工作。

#include <cstdlib>
#include <iostream>
#include <string>
using namespace std;

int main(int argc, char *argv[])
{
  int i;
  int desDateYear = 21;
  int todayDateYear = 15;
  int calcDayInt = 4;
  int calcDateYear = todayDateYear;  

  if(desDateYear>todayDateYear)
    {
      for (i = 0; i < ((desDateYear-todayDateYear)+1); i++)
      {
          if ((calcDateYear)%4==0)
          {
            for (i=0; i<2; i++)
            {
              calcDayInt++;
              if(calcDayInt==8)
              {
                calcDayInt=1;
              }
            }
          }
          if ((calcDateYear)%4!=0)
          {
              calcDayInt++;
              if(calcDayInt==8)
              {
                calcDayInt=1;
              }
          }
          calcDateYear++;
      }
    }
    cout<<calcDayInt;
    system("PAUSE");
    return EXIT_SUCCESS;
}

You are stuck in an infinite loop. 您陷入无限循环。

The inner for loop reuses the counter i from the outer loop and overwrites its value. 内部for循环从外部循环重用计数器i并覆盖其值。 Thus the termination condition for the outer loop is never met and the loop never finishes. 因此,永远不会满足外部循环的终止条件,并且循环永远不会结束。

You can use a different variable for the inner loop by changing the loop header to something like 您可以通过将循环标头更改为以下内容来为内部循环使用其他变量

for (int i=0; i<2; i++)

Bonus points for you if you can figure out why it still works for some values and what the exact boundaries are at which it starts to get stuck. 如果您能弄清楚为什么它仍然适用于某些值以及开始陷入困境的确切界限,则可以为您提供加分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM