Python 我怎样才能把小数分解成年和日?
我是一名初级程序员,以下是迄今为止我的程序:Python 我怎样才能把小数分解成年和日?,python,Python,我是一名初级程序员,以下是迄今为止我的程序: def getYearsandDays(): c = eval(input("Enter a number: ")) d = c // 1 e = (c - d) * 365 f = e // 1 return f,d print(d , "years and", f, "days") () 例如,假设c
def getYearsandDays():
c = eval(input("Enter a number: "))
d = c // 1
e = (c - d) * 365
f = e // 1
return f,d
print(d , "years and", f, "days")
()
例如,假设c是1.34。将其转换为整数将得到1年=d。现在1.34-1给你0.34。乘以356,得到124.1=e。将其设为整数将得到124天=f。所以1.34年是1年,124天
我已经知道我的打印函数是错误的,因为我一直在思考如何获得这样的输出:
6 years and 1 day
1 year and 137 days
67 days
而不是:
6 years and 1 days
1 years and 137 days
0 years and 67 days
我猜我可能需要将整数转换回字符串,并生成If-Then语句,但我不是100%确定。这就是我要做的:
def years_and_days():
# Use input instead of raw_input if you're using Python 3.x
time = float(raw_input('Enter a number: '))
years = int(time)
days = int((time - int(time)) * 365)
if years:
print years, 'years' if years > 1 else 'year',
if days:
print days, 'days' if days > 1 else 'day'
用法:
>>> years_and_days()
Enter a number: 3
3 years
>>> years_and_days()
Enter a number: 1.34
1 year 124 days
>>> years_and_days()
Enter a number: 0.32
116 days
这就是我要做的:
def years_and_days():
# Use input instead of raw_input if you're using Python 3.x
time = float(raw_input('Enter a number: '))
years = int(time)
days = int((time - int(time)) * 365)
if years:
print years, 'years' if years > 1 else 'year',
if days:
print days, 'days' if days > 1 else 'day'
用法:
>>> years_and_days()
Enter a number: 3
3 years
>>> years_and_days()
Enter a number: 1.34
1 year 124 days
>>> years_and_days()
Enter a number: 0.32
116 days
如果c是您的输入:
你可以做c MOD 1…这会给你小数点。
要得到整数,你只需要c-cmod1…剩下的计算就可以了
mod是模数的缩写,它基本上是一种计算剩余部分的方法。所以5mod2是5/2或1的余数
不知道你用的是什么语言,但是如果你在谷歌上搜索模数和你的语言名称,你就能找到你想要的
希望有帮助
def getYearsandDays():
c = eval(input("Enter a number: "))
d = c - c%1 //years
e = (c -d) * 365 //days in decimal format
f = e - e%1 // days in integer format...you probably would get away with just rounding here too...
return f,d
print(d , "years and", f, "days")
()
如果c是您的输入:
你可以做c MOD 1…这会给你小数点。
要得到整数,你只需要c-cmod1…剩下的计算就可以了
mod是模数的缩写,它基本上是一种计算剩余部分的方法。所以5mod2是5/2或1的余数
不知道你用的是什么语言,但是如果你在谷歌上搜索模数和你的语言名称,你就能找到你想要的
希望有帮助
def getYearsandDays():
c = eval(input("Enter a number: "))
d = c - c%1 //years
e = (c -d) * 365 //days in decimal format
f = e - e%1 // days in integer format...you probably would get away with just rounding here too...
return f,d
print(d , "years and", f, "days")
()
此代码不起作用,因为您在返回后有一个打印。最后一行的是什么意思?此代码不起作用,因为您在返回后有一个打印。最后一行的是什么意思?顺便说一句,我们刚刚意识到这是python。在本例中,使用%符号表示模数。顺便说一句,这是python。在本例中,使用%符号表示模数。