Home > database >  How to correctly print out Leap year?
How to correctly print out Leap year?

Time:02-05

I'm attempting to make a calendar for a project. The program is working however, my calculations are incorrect in the sense that my program thinks, for example, that 2022 is a leap year and 2024 is not. How do I fix this, please?? I've tried changing the bool statement but nothing seems to work. Am I calling it correctly?

I'm really struggling. I'm still new to c so my apologies if this is a bad question.

#include <iostream>

int month, day, year, start = 0;

#define MONTHS_PER_YEAR 12

const unsigned short DAYS_PER_MONTH[MONTHS_PER_YEAR] =
    {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

const char MONTH_NAMES[MONTHS_PER_YEAR][10] =
    {"January",   "February", "March",    "April",
     "May",       "June",     "July",     "August",
     "September", "October",  "November", "December"};

int leapYear(int year)
{
    return (((year % 400) == 0) || ((year % 4 == 0)&& !(year % 100 == 0)));
}
int day_of()
{
    int subset_days[] = {0, 3, 2, 5, 3, 5, 1, 4, 6, 2, 4};
    if (month < 3)
        year--;
    return ((year   year / 4 - year / 100  year /400   subset_days[month - 1]  day) % 7);
}

void printMonth()
{
    int number_of_days = leapYear(year);
    start = day_of();
    int count = 0; 
    int days_per = DAYS_PER_MONTH[month - 1];
    if(leapYear(year) && month == 2)
    {
        days_per = DAYS_PER_MONTH[month-1]   1;
    }

    if (start == 6) 
    {
      start = -1;
      std::cout << "  ";
    }
    for (count = 0; count <= start; count  )
    {
      if (count > 0)
        std::cout << "   ";
      else
        std::cout << "   ";
    }
    for (day = 1; day <= days_per; day  )
    {
        if (  count > 6) 
        {
            count = 0;
            if (day > 9)
                std::cout << day << '\n';
            else
                std::cout << day << '\n' << " ";
        }
        else
        {
            if (day >= 9)
                std::cout << day;
            else
                std::cout << day << " ";
            std::cout << " ";
        }
    }
    std::cout << std::endl;
  }

// Controls operation of the program.
int main()
{  
    std::cout << "Enter the month: ";
    std::cin >> month;
    std::cout << "Enter the year: ";
    std::cin >> year;
    std::cout << MONTH_NAMES[month - 1] << " " << year << std::endl;
    std::cout << "Su" << "  "<< "M" << "  "<< "T"<< "  " << "W" << " " << "Th" << "  " << "F" << " " << "Sa\n";
    printMonth();
    return 0;
}

CodePudding user response:

Try like this in the leap Year function

return (((year % 400) == 0) || ((year % 4 == 0)&& !(year % 100 == 0)));

CodePudding user response:

I'd just answer the title


with c 20 you can use std::chrono to do it

std::chrono::year{y}.is_leap()

godbolt link

  •  Tags:  
  • Related