根据年月日,输出是一年中的第几天
1 先不考虑闰年,公式 : 天数 = 每月的天数相加(只加到前一个月)+ 天数(日期)
2 是闰年的话 且超过了2月,那么最后天数再加1
3 闰年判断标准 : 能被4整除,但不能被100整除 或者能被400整除
import java.util.Scanner;
public class Main {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
//从用户输入获取到年月日
while(sc.hasNext()){
int year = sc.nextInt();
int month = sc.nextInt();
int day = sc.nextInt();
//定义一个数组,将每个月的天数写在上面 先不考虑闰年
int sum= 0;
int[] days = {31,28,31,30,31,30,31,31,30,31,30,31};
//按照月份遍历,遍历到几月就加到几月的前一个月,当前月的通过天数相加
for(int i=0;i<month-1;i++){
sum +=days[i];
}
//再加上天数
sum +=day;
//再判断是不是闰年,是的话,如果又超过2月,则多加一天
if(month>2 && isLeap(year)){
sum +=1;
}
System.out.println(sum);
}
}
public static boolean isLeap(int n){
//闰年标准:能被4整除 但是不能被100整除 或者能被400整除
if(n%4==0 && n%100!=0 || n%400==0){
return true;
}else{
return false;
}
}
}


京公网安备 11010502036488号