首页 文章

打印月份和年份的月历

提问于
浏览
-3

一旦用户输入有效输入(由空格分隔的两个整数),以与UNIX cal命令的输出类似的格式打印日历 . 例如,如果用户输入03 2014,则输出应为:

http://imgur.com/NCKOFL0

我意识到我之前问了一个类似的问题,但我根本无法理解答案 . 我觉得我应该从基础知识开始,这样我就可以学习如何在给出一个月和一年的输入的基础上打印月度日历 .

我提供了下面的代码,只能打印出下一个月的游行,因为我们将每个不同年份的每个不同月份从不同的一天开始,代码变得越来越复杂,所以我想知道我应该如何开始做这个代码 .

因为我的教授不喜欢使用远远超出我的知识水平的东西,所以请不要提前 .

#include <stdio.h>

int main()
{
 int k, rmd;

 printf("     March 2014\n");
 printf(" Su Mo Tu We Th Fr Sa\n");

 for(k=1;k<32;++k){
     if(k==1){
         printf("                   %2d\n", k);
     }
     else if(k%7 == 1){
         printf(" %2d\n",k);
     }

     else{
         printf(" %2d",k);
     }
}
return 0;
}

3 回答

  • 0

    基本方法很简单:

    找一年您知道会发生什么的一年(例如2014-3-1是星期六) . 然后考虑一年365天(包括7 * 52 1天......)和366天年的情况 . 之后你只需要知道leap years何时发生 .

    您可以找到您将考虑的第一年的开始日期,也可以包含向后计算(例如,在此之前365天发生的事情) - 第一个更简单,但引入了额外的约束 .

  • 0
    Step 1:  Given the month and year, determine the day of the week for the 1st of the month
    Step 1a: You already know how to do that, since I saw one of your previous posts
    Step 2:  Compute how many spaces you need to print so that 1 is in the correct column
    Step 3:  Print additional numbers until you reach Saturday
    Step 3a: Print a newline character after printing the number for Saturday
    Step 4:  Keep outputting numbers and newlines till you reach the end of the month
    Step 4a: Remember that February has 29 days for leap years
    Step 5:  Print a newline if the month didn't end on a Saturday
    Step 5a: Print one more newline just for good measure
    
  • 0

    你可以阅读this以了解如何获得星期几 . 然后你可以使用这段代码打印一年 month 年份 year 的日历 .

    d=2+ ((153 * (month + 12 * ((14 - month) / 12) - 3) + 2) / 5)+ (365 * (year + 4800 -((14-month) / 12)))+ ((year + 4800 - ((14 - month) / 12)) / 4)- ((year + 4800 - ((14 - month) /12)) / 100)+ ((year + 4800 - ((14 - month) / 12)) / 400)- 32045;
    d=d%7;
    i=0;
    while(i<d)
    {
     printf("  ");
     i++;
    }
    //let dd be the number of days in month `month-year`
    for(j=1;j<=dd;j++)
    {
      if(d<7)                    //to get the sunday date to next line
      {
       printf("%d ",j);
       d++;
      }
      else
      {
       printf("\n");
       printf("%d ",j)
       d=1;
      }
    
    }
    

    它将打印输出

    sun mon tue wed thu fri sat
        1    2  3   4   5   6
    7
    

    形成 .

相关问题