[英]How to convert months to years and months?
如何將一些月份轉換為年份和月份?
23 個月 = 1 年 11 個月
嘗試使用這樣的代碼
round(23 / 12, 2) = 1.92
這沒有給我預期的答案。
你大概想要divmod
:
total_months = 23
years, months = divmod(total_months, 12)
print(f"{years} years, {months} months")
# 1 years, 11 months
內置的divmod(x, y)
函數返回(x // y, x % y)
的 2 元組 - 換句話說, x
除以y
的整數商,以及除法后的余數。
當然,你總是可以自己用這些操作做同樣的事情:
total_months = 23
years = total_months // 12
months = total_months % 12
在 C 中,你會這樣做:
#include <stdio.h>
int main(int argc, char *argv[])
{
int months = 67;
int years = 0;
for(months; months>11; months-=12)
{
years++;
}
printf("years : %i\n", years);
printf("months: %i\n", months);
return 0;
}
我猜 Python 也支持任何類型的循環。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.