如何根据总数获得年数和月数?

问题描述 投票:-2回答:2

我想根据总数计算多少年和几个月。这是我到目前为止所做的。

int total = 23;
float test = total/12;

entYears.Text = //number of years here;
entMonths.Text = //number of months here;
c#
2个回答
2
投票

年数将是total/12。另一方面,月份将为total%12

一年是12个月,所以要使用年份除法,要获得年数。计算年份后,月份将是“剩余”,这是模数12起作用的地方。

23/12将计算为1,因此为1年。 23%12的评估值为11。这意味着23是1年11个月。


0
投票

您需要使用remainder operator%):

int total = 23;
int years = total / 12;
int months = total % 12;

Try it online

© www.soinside.com 2019 - 2024. All rights reserved.