public static int CalcMoneyZero(int totalMoney, out int ownerMoney, Func<int, int> addMoneyFunc, Func<int, int> subMoneyFunc)
{
int maxMonth = 100 * 12; // 最高100年
for(int monthNub = 0; monthNub <= maxMonth; monthNub++)
{
var monthAddNum = addMoneyFunc(monthNub);
var monthSubNum = subMoneyFunc(monthNub);
if(totalMoney + monthAddNum >= monthSubNum)
{
totalMoney = totalMoney + monthAddNum - monthSubNum;
}
else
{
ownerMoney = totalMoney;
return monthNub;
}
}
ownerMoney = totalMoney;
return maxMonth;
}
测试输入:
当前身上: 5000 每月进账: 1000 每月支出: 2000
第5个月月光,还剩0
int monthTotal = CalcMoneyZero(5000, out int ownerMoney, (a) => 1000, (a) => 2000);
if (monthTotal > 12)
{
Console.WriteLine($"第{monthTotal / 12}年{monthTotal % 12}月月光,还剩{ownerMoney}");
}
else
{
Console.WriteLine($"第{monthTotal}个月月光,还剩{ownerMoney}");
}