如何將一些月數轉換為年和月?23個月=1年零11個月嘗試使用這樣的代碼round(23 / 12, 2) = 1.92這并沒有給我預期的答案。
2 回答

Cats萌萌
TA貢獻1805條經驗 獲得超9個贊
在 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也支持任何類型的循環。

慕森王
TA貢獻1777條經驗 獲得超3個贊
您可能想要divmod:
total_months = 23
years, months = divmod(total_months, 12)
print(f"{years} years, {months} months")
# 1 years, 11 months
內置divmod(x, y)函數返回一個 2 元組(x // y, x % y)- 換句話說,除以 的整數商xy,以及除法后的余數。
當然,您始終可以通過這些操作自己做同樣的事情:
total_months = 23
years = total_months // 12
months = total_months % 12
添加回答
舉報
0/150
提交
取消