我已经编写了这段代码,我想知道问题出在哪里。它应该是一个年龄计算器,它使用名为YOB“出生年份”的列表,并且我想从列表中读取值,以从列表中的年龄开始计算最小年龄,最大年龄和中年年龄。但是当计算中年是636.1428xxxxxxx时,最小的是21岁,最大的是2096年。现在我知道最小的应该是21岁,年龄最大的应该是87岁,中年应该是49岁。
import datetime
import statistics
counts = 0
sumYear = 0
oldAge = 0
youngAge = 110
YOB = [1999, 1932, 1887, 1982, -76, 1963, 0]
for years in YOB:
years = datetime.datetime.now().year - years
if years > 0:
counts += 1
sumYear += years
if years < youngAge:
youngAge = years
print('Test3')
if years > oldAge:
oldAge = years
print('test4')
print("middle age is ", sumYear / counts, "year.")
print("the youngest are", youngAge, " and the oldest are ", oldAge)
答案 0 :(得分:1)
假设-76和0不是有效的出生年份,那么您的最大年龄为133(出生于1887年)。 您可以通过将将youngAge和oldAge变量更改为以下年份检查项的if子句来忽略-76岁和0岁出生的人。我还更改了您传递给year的变量,以将年的定义保留为单一含义(仅是年龄),并将YOB迭代项保留为刚出生的年份。
### Summary of Ages for birth years
import datetime
import statistics
counts = 0
sumYear = 0
oldAge = 0
youngAge = 110
YOB = [1999, 1932, 1887, 1982, -76, 1963, 0]
for year in YOB:
years = datetime.datetime.now().year - year
print(year, years)
if year > 0:
counts += 1
sumYear += years
if years < youngAge:
youngAge = years
print('Test3')
if years > oldAge:
oldAge = years
print('test4')
print("middle age is ", sumYear / counts, "year.")
print("the youngest are", youngAge, " and the oldest are ", oldAge)