-
要求:
有些西方人比较迷信,如果某个月的13号正好是星期五,他们就会觉得不太吉利。请你编写一个程序,统计出在某个特定的年份中,出现了多少次既是13号又是星期五的情形,以帮助你的迷信朋友解决难题。 -
说明:
- (1)一年一般有365天,闰年有366天。所谓闰年,是指能被4整除且不能被100整防的年份,或是既能被100整除也能被400整除的年份。
- (2)已知1998年1月1日是星期四·而且用户输入的年份肯定大于或等于1998年。
- (3)程序的输人为某个特定的年份,输出为这一年中,出现了多少次既是13号又是星期五角情形。
-
源代码:
package qi_mo;
import java.util.Scanner;
public class Test8 {
static int getweekoffirstday(int y) {
int i = 1998, week = 3;
int days = 0;
for (i = 1998; i < y; i++) {
if (i % 400 == 0 || (i % 4 == 0 && i % 100 != 0))
days += 366;
else
days += 365;
}
return (days + week) % 7;
}
static void print(int y) {
int day[][] = { { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 },
{ 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 } };
int week = getweekoffirstday(y), flag = y % 400 == 0 || (y % 4 == 0 && y % 100 != 0) ? 1 : 0;
int times = 0, i, days = 0;
for (i = 0; i < 12; i++) {
if ((days + 12 + week) % 7 == 4)
times++;
days += day[flag][i];
}
// System.out.println(times);
System.out.println("出现了" + times + "次即是13号又是星期五的情形");
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int y = sc.nextInt();
print(y);
}
}
- 测试结果: