fork(2) download
  1. #include <ctime>
  2. #include <cstdio>
  3.  
  4. const char *months[]={
  5. "\nJanuary","\nFebruary","\nMarch","\nApril","\nMay","\nJune","\nJuly","\nAugust","\nSeptember","\nOctober","\nNovember","\nDecember"
  6. };
  7.  
  8. int month_days[] = {0, 31, 28, 31, 30, 31, 30, 31 ,31 ,30, 31, 30, 31};
  9.  
  10. int first_day_year(int year)
  11. {
  12. int first_day;
  13. int x;
  14. int y;
  15. int z;
  16.  
  17. x = (year - 1.)/4.0;
  18. y = (year - 1.)/100.;
  19. z = (year - 1.)/400.;
  20.  
  21. first_day = (year + x - y + z) %7;
  22.  
  23. return first_day;
  24. }
  25.  
  26. int leapyear(int year)
  27. {
  28. if((year% 4 == 0 && year%100 != 0) || year%400 == 0){
  29. month_days[2] = 29; //agora [2] está certo devido ao primeiro ponto
  30. return 1;
  31. }
  32.  
  33. //else é desnecessário basta fazer o retorno diretamente
  34. return 0;
  35. }
  36.  
  37. int calendar(int month, int year, int first_day)
  38. {
  39. int i;
  40.  
  41. printf("%s %d\n\n", months[month-1], year); //month-1 para imprimir o correto
  42. printf("Sun Mon Tue Wed Thu Fri Sat\n");
  43.  
  44. for(i = 1; i < month; i++) //agora começa em 1
  45. {
  46. //+month_days[i] e não +month_days[month] que era o problema maior
  47. first_day = ((first_day + month_days[i])%7);
  48. }
  49.  
  50. for(i = 1; i <= 1 + first_day * 5; i++)
  51. {
  52. printf(" ");
  53. }
  54.  
  55. for(i = 1; i <= month_days[month]; i++)
  56. {
  57. printf("%2d", i);
  58.  
  59. if((i + first_day)%7 > 0)
  60. printf(" ");
  61. else
  62. printf("\n ");
  63. }
  64. }
  65.  
  66. int main(void)
  67. {
  68. int year;
  69. int month;
  70. int first_day;
  71.  
  72. do{
  73. printf("Enter a month (1 - 12): ");
  74. scanf("%d", &month);
  75. } while (month < 1 || month > 12);
  76.  
  77. do{
  78. printf("Enter a year (1000 - 3000): ");
  79. scanf("%d", &year);
  80. } while (year < 1000 || year > 3000);
  81.  
  82. first_day = first_day_year(year);
  83.  
  84. leapyear(year);
  85.  
  86. calendar(month, year, first_day);
  87.  
  88. printf("\n");
  89.  
  90. return 0;
  91. }
Success #stdin #stdout 0s 16064KB
stdin
2
2004
stdout
Enter a month (1 - 12): Enter a year (1000 - 3000): 
February 2004

Sun  Mon  Tue  Wed  Thu  Fri  Sat
  1    2    3    4    5    6    7
  8    9   10   11   12   13   14
 15   16   17   18   19   20   21
 22   23   24   25   26   27   28
 29