我想根据总数计算多少年和几个月。这是我到目前为止所做的。
int total = 23;
float test = total/12;
entYears.Text = //number of years here;
entMonths.Text = //number of months here;
年数将是total/12
。另一方面,月份将为total%12
。
一年是12个月,所以要使用年份除法,要获得年数。计算年份后,月份将是“剩余”,这是模数12起作用的地方。
23/12将计算为1,因此为1年。 23%12的评估值为11。这意味着23是1年11个月。
您需要使用remainder operator(%
):
int total = 23;
int years = total / 12;
int months = total % 12;