1970年出生的人一生有多少个闰年?(70岁寿命)
1970年出生的人一生有多少个闰年?(70岁寿命)
本文将使用Java程序计算一个出生于1970年、寿命70岁的人一生中会遇到多少个闰年。
Java 代码
public class LeapYearCalculator {
public static void main(String[] args) {
int birthYear = 1970;
int lifeExpectancy = 70;
int leapYearCount = 0;
for (int year = birthYear; year < birthYear + lifeExpectancy; year++) {
if (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) {
leapYearCount++;
}
}
System.out.println('This person can experience ' + leapYearCount + ' leap years in their lifetime.');
}
}
代码解释
birthYear表示这个人的出生年份,设为1970;lifeExpectancy表示这个人的寿命长度,设为70岁;leapYearCount表示这个人能经历的闰年数量,初始值为0;- 使用
for循环遍历这个人的出生年份到他预期的死亡年份之间的每一年; - 在循环中,使用条件语句判断当前年份是否是闰年,如果是,则将
leapYearCount加1; - 最后,输出这个人能经历的闰年数量。
运行结果
This person can experience 17 leap years in their lifetime.
因此,这个人在他的一生中能经历17个闰年。
原文地址: https://www.cveoy.top/t/topic/jYLE 著作权归作者所有。请勿转载和采集!