Questions algorithm to calculate the number of days of training
Requirements:
writing a function evaluation on a certain day (**** ** **) is the first few days of the year. Tip: To consider leap year, leap year, February is 29 days (leap year conditions: a multiple of 4 but not multiple of 100, or multiples of 400). Write the main function, enter the date, test the function and output.
Input format:
Press "yyyy mm dd" date input format
output formats:
outputs the calculation result by an integer
sample input:
1,990,510
Sample Output:
130
data size and conventions:
date valid according to the actual input
Code:
import java.util.Scanner;
public class 天数计算
{
// 定义函数计算天数
public static int Day(int year, int month, int day) {
int sum = 0;
for (int i = 1; i < month; i++)
{
switch (i)
{
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
sum += 31;
break;
case 4:
case 6:
case 9:
case 11:
sum += 30;
break;
case 2:
//判断是否为闰年
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)
{
sum += 29;
} else
{
sum += 28;
}
default:
break;
}
}
//返回当前年的值
return sum + day;
}
public static void main(String[] args) {
// 编写函数求某年某月某日(**** ** **)是这一年的第几天 。提示:要考虑闰年,
// 闰年的2月是29天(闰年的条件:是4的倍数但不是100的倍数,或者是400的倍数)。
// 编写主函数,输入年月日,测试该函数并输出结果。
Scanner sc = new Scanner(System.in);
//输入年月日
int year = sc.nextInt();
int month = sc.nextInt();
int day = sc.nextInt();
System.out.println(Day(year, month, day));//调用函数并且输出
}
}
Sample input:
1990 5 10
Sample output:
130