题目
写一个程序,输入年份和月份,输出该月包含了多少天?
准备
根据日历的规则可知:无论什么年份,1、3、5、7、8、10、12月都是31天,4、6、9、11月都是30天,闰年2月28天,平年2月29天。
思路
判断是输入否是2月,如果是再判断是否是闰年,随后输出对应数即可。
实现
C/C++代码如下:
#include <stdio.h>
// 数组用来存每个月包含的天数,这里存的是平年的天数
// 数组以0开头,月份以1开头,不想再去考虑数组与月份的对应关系,索性弃掉数组位置为0的那块空间吧
const int DAY_OF_MONTH[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
// 该函数根据年月,返回该月包含的天数
int getDays(int year, int month){
// 判断月份是否为2并且年份是否为闰年,是的话返回29,方法结束
if((month == 2) && ((year % 4 == 0) && (year % 100 != 0) || (year % 400 == 0))){
return 29;
}
// 不是的话会执行到该处,直接返回月份数组中的天数。
return DAY_OF_MONTH[month];
}
// 主函数用于测试
int main(){
int year, month, day;
printf("请输入年:");
scanf("%d", &year); // 输入函数
printf("请输入月:");
scanf("%d", &month); // 输入函数
day = getDays(year, month);
printf("%d 年 %d 月共有 %d 天", year, month, day); // 输出函数
return 0;
}
Java代码如下:
public class Test01 {
// 数组用来存每个月包含的天数,这里存的是平年的天数
// 数组以0开头,月份以1开头,不想再去考虑数组与月份的对应关系,索性弃掉数组位置为0的那块空间吧
static final int[] DAY_OF_MONTH = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
// 根据年月,返回该月包含的天数
static int getDays(int year, int month){
// 判断月份是否为2并且年份是否为闰年,是的话返回29,方法结束
if((month == 2) && ((year % 4 == 0) && (year % 100 != 0) || (year % 400 == 0))){
return 29;
}
// 不是的话会执行到该处,直接返回月份数组中的天数。
return DAY_OF_MONTH[month];
}
// 主方法用于测试
public static void main(String[] args) {
int year, month, day;
Scanner scanner = new Scanner(System.in);
System.out.println("请输入年:");
year = scanner.nextInt();
System.out.println("请输入月:");
month = scanner.nextInt();
day = getDays(year, month);
System.out.printf("%d 年 %d 月共有 %d 天", year, month, day);
}
}
结果
总结
无。