printing calendar with wrong days

Asked

Viewed 90 times

-2

good day galley I made an agoritimo that generates the calendar of a given year however for bisext years it is returning days correctly but for years not bisextos it brings dates for different days, I upgraded the function Legend to generate the same for a specific month through user choice and also it is not working what I did wrong?

#include <iostream>

// pega primeiro dia do mes
int primeiro_dia(int mes, int ano)
{
 int a = ((14 - mes)/12);
 int y = (ano-a);
 int m = ((mes+(12*a))-2);
 int dia = 1;

 return dia = ((dia+y+(y/4)-(y/100)+(y/400)+((31*m)/12))%7);
}

//imprime calendario de todos os meses do ano
void calendario(int ano)
{
 int month_days[12] = {31, 28, 31, 30, 31, 30, 31 ,31 ,30, 31, 30, 31};

 month_days[1] = (ano%4 == 0 || ano%400 == 0 && ano%100 != 0) ? 29 : 28;

 const char *months[12]={ "January","February","March","April","May","June","July","August","September","October","November","December" };

 std::cout<<"\n";

 for(int mes = 1; mes <=12; mes++)
 {
  std::cout<<"Month: "<<months[mes-1]<<"-"<<ano<<"\nSun Mon Tue Wed Thu Fri Sat\n";

  int primeiro = primeiro_dia(mes, ano); //pega primeiro dia do mes

  for(int i=0; i < primeiro; i++)
  std::cout<<"    ";

  for(int dia = 1; dia <= month_days[mes-1]; dia++)
  {
   printf("%3d ",dia);
   primeiro++;
   if(primeiro%7 == 0)std::cout<<"\n";
  }
  std::cout<<"\n\n";
 }
}

// imprime calendario de mes especifico
void mes_calendario(int mes, int ano)
{
 int month_days[12] = {31, 28, 31, 30, 31, 30, 31 ,31 ,30, 31, 30, 31};

 month_days[1] = (ano%4 == 0 || ano%400 == 0 && ano%100 != 0) ? 29 : 28;

 const char *months[12]={ "January","February","March","April","May","June","July","August","September","October","November","December" };

 std::cout<<"\n";

  std::cout<<"Month: "<<months[mes-1]<<"-"<<ano<<"\nSun Mon Tue Wed Thu Fri Sat\n";

  int primeiro = primeiro_dia(mes, ano); //pega primeiro dia do mes

  for(int i=0; i < primeiro; i++)
  std::cout<<"    ";

  for(int dia = 1; dia <= month_days[mes-1]; dia++)
  {
   printf("%3d ",dia);
   primeiro++;
   if(primeiro%7 == 0)std::cout<<"\n";
  }
  std::cout<<"\n\n";
}

int main()
{
 int ano;
 std::cout<<"Digite o ano: ";
 std::cin>>ano;
 calendario(ano);
 return 0;
}

1 answer

1


This test of yours:

month_days[1] = (ano%4 == 0 || ano%400 == 0 && ano%100 != 0) ? 29 : 28;

is wrong. Right is right:

month_days[1] = (((ano % 4 == 0) && (ano % 100 != 0)) || (ano % 400 == 0)) ? 29 : 28;
  • identified another error the variable handle int first = first day(year, month); it is to catch int first = first day(month, year);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.