如何将月份转换为年和月?

如何将一些月数转换为年和月?

23个月=1年零11个月

尝试使用这样的代码

round(23 / 12, 2) = 1.92

这并没有给我预期的答案。


慕少森
浏览 102回答 2
2回答

Cats萌萌

在 C 中你可以这样做:#include <stdio.h>int main(int argc, char *argv[]){&nbsp; &nbsp; int months = 67;&nbsp; &nbsp; int years = 0;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; for(months; months>11; months-=12)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; years++;&nbsp; &nbsp; }&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; printf("years : %i\n", years);&nbsp; &nbsp; printf("months: %i\n", months);&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; return 0;}我想Python也支持任何类型的循环。

慕森王

您可能想要divmod:total_months = 23years, 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 = 23years = total_months // 12months = total_months % 12
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python