大致的思路是这样的,就是把输入的月份之前的月份天数加起来,在加上输入的月份的日数。
比如:3月2日,就是1、2月份的天数加起来,再加上2
还有一点就是平年和闰年2月份的天数是不同的。这里要进行平闰年的判断。
以下的代码是用Java写的:总之,是一个for循环整体计算月的总天数的。
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
// 定义变量,分别保存用户输入的年月日变量
int year, month, day;
// 定义一个变量,用来保存这是该年的第几天
int total = 0;
// 获得用户输入的年月日
Scanner scanner = new Scanner(System.in);
System.out.println("请输入一个年份吧:");
year = scanner.nextInt();
System.out.println("请输入一个月份吧:");
month = scanner.nextInt();
System.out.println("请输入一个日吧:");
day = scanner.nextInt();
// 判断是平年还是闰年
for (int foremonth = 1; foremonth < month; foremonth++) {
switch (foremonth) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
total += 31;
break;
case 4:
case 6:
case 9:
case 11:
total += 30;
break;
}
// 闰年,二月份为29天
if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
if (foremonth == 2) {
total += 29;
}
} else {
// 如果是平年,二月份为28天
if (foremonth == 2) {
total += 28;
}
}
}
// 加上这个月的天数
total = total + day;
System.out.println("今天是今天第:" + total + "天");
}
}