我找不到正确的循环来使这段代码工作!
我尝试使用 while 循环,我可以让 Python 显示用户选择的两年之间的所有闰年,但不是我被要求使用的格式。
start = int(input("Enter start year: "))
end = int(input("Enter end year: "))
if start < end:
print ("Here is a list of leap years between " + str(start) + " and " + str(end) + ":")
while start < end:
if start % 4 == 0 and start % 100 != 0:
print(start)
if start % 100 == 0 and start % 400 == 0:
print(start)
start += 1
if start >= end:
print("Check your year input again.")
问题描述:年份能被4整除就是闰年,除了能被100整除的年份是 只有当它也能被 400 整除时才是闰年。编写一个程序计算出 用户指定的两年之间的闰年。该程序应列出 10 个飞跃 每行年,列出的每一年之间用逗号分隔,末尾有一个句号,如 在以下输入/输出示例中:
Enter start year: 1000
Enter end year: 1200
Here is a list of leap years between 1000 and 1200:
1004, 1008, 1012, 1016, 1020, 1024, 1028, 1032, 1036, 1040,
1044, 1048, 1052, 1056, 1060, 1064, 1068, 1072, 1076, 1080,
1084, 1088, 1092, 1096, 1104, 1108, 1112, 1116, 1120, 1124,
1128, 1132, 1136, 1140, 1144, 1148, 1152, 1156, 1160, 1164,
1168, 1172, 1176, 1180, 1184, 1188, 1192, 1196, 1200.
提示:答案使用 for 循环遍历从开始年份到结束年份的所有年份 年末,作为闰年计数器的额外变量,以及各种 if 和 if-else 语句 在循环中检查年份是否是闰年,是否需要逗号,以及是否换行 是需要的。
最佳答案
条件应该不同——
if (start % 4 == 0 and start % 100 != 0) or (start % 4 == 0 and start % 400 == 0):
另外,为了将结束年份包含在范围内,循环条件应为 -
while start <= end:
关于Python闰年计算器(用户选择的两年之间),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54390620/