c语言:求某年某月的天数(2种方法)

如果要求某年某月的天数,除了2月的天数会跟是否是平年闰年有关,其他月份的天数都是固定的,所以2月是这里的特殊值,要想知道2月的天数,必须要知道那一年是平年还是润年,以下提供2种思路。

1.利用switch语句

#include<stdio.h>
int main()
{
    int year, mouth, days;
    printf("请输入年,月:");
        scanf("%d,%d", &year, &mouth);
    switch(mouth)
    { case 1:
      case 3:
      case 5:
      case 7:
      case 8:
      case 10:
      case 12:days = 31;  break;
      case 4:
      case 6:
      case 9:
      case 11:days = 30; break;
      case 2:
          if (year % 400 == 0 || year % 4 == 0 && year % 100 != 0)
              days = 29;
          else
              days = 28; break;


    }
    printf("%d年%d月的天数是%d天\n", year, mouth, days);
    return 0;
}

2.利用二维数组

#include<stdio.h>
int main()
{
    int year, mouth, leap;
    int arr1[2][13] = { { 0,31,28,31,30,31,30,31,31,30,31,30,31 },
                      { 0,31,29,31,30,31,30,31,31,30,31,30,31 } };
    printf("请输入年月:");
    scanf("%d %d", &year, &mouth);
    if (year % 400 == 0 || year % 4 == 0 && year % 100 != 0)
        leap = 1;
    else
        leap = 0;
    printf("天数为%d",arr1[leap][mouth]);
    return 0;
}
    

二维数组不仅可以求某年某月的天数,还可以求某一天是这一年的第几天,具体请看我的另一篇博客。C语言:求某一天是这年的第几天

猜你喜欢

转载自blog.csdn.net/m0_75115696/article/details/128701804