通过引用传递的struct导致垃圾值

时间:2016-06-03 04:11:23

标签: c++

通过Project Euler并完成我认为的一个简单问题。出于某种原因,当通过引用传递结构Date时,当我尝试引用或分配它们时会导致垃圾值。有什么想法吗?

#include <iostream>

using namespace std;

bool isLeapYear(int year)
{
    // century 
    if ((year % 100 == 0) && (year % 400 == 0))
        return true;
    // not a century
    else if ((year % 100 != 0) && (year % 4 == 0))
        return true;

    return false;
}

enum Months {JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC};

struct Date
{
    int year;
    Months month;
    int day;
};

int calculateNumberOfDays(const Date& begin, const Date& end)
{
    int numberOfDays = 0;

    //PROBLEM: This loop never runs... Upon running it through the debugger
    //         the value of year is garbage i.e. -859382918
    //         This results in the loop not being entered and the value 
    //         (numberOfDays) being returned as 0
  for (int year = begin.year; year < end.year; year++)
    {
        if (isLeapYear(year))
            numberOfDays += 366;
        else
            numberOfDays += 365;
    }

    //TODO: Finish for final year

    return numberOfDays;
}

int main()
{
    int numberOfDays = 0;
    int year = 1900;
    Months month = JAN;
    int day = 1;


    Date begin = { 1990, JAN, 1 };
    Date end = { 1901, DEC, 31 };

    cout << calculateNumberOfDays(begin, end) << endl;


    return 0;
}

1 个答案:

答案 0 :(得分:2)

begin日期是在end日期之后,因此循环不会运行。交换两个日期会导致循环正确运行。

您的调试器可能会因为有两个名为year的变量而感到困惑。这让你走错了路。