【问题标题】:print monthly calendar given month and year打印给定月份和年份的月历
【发布时间】:2014-03-23 09:28:27
【问题描述】:

一旦用户输入了一个有效的输入(两个用空格分隔的整数),打印出来 日历格式类似于 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;
}

【问题讨论】:

标签: c date


【解决方案1】:

基本方法很简单:

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

您可以找到您将考虑的第一年的开始日期,也可以合并反向计算(例如,在此之前 365 天发生的事情) - 第一个更简单,但引入了额外的限制。

【讨论】:

    【解决方案2】:
    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
    

    【讨论】:

      【解决方案3】:

      您可以阅读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
      

      表格。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-04-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多