我正在做一个项目,我必须计算年初至今每日复利的交易。目前我只是没有兴趣获得当前的余额。我相信我的问题是关于foreach循环,但我不确定我在哪里犯了错误。它正在经历这些日子,但是没有任何兴趣被应用或者运行总体没有正常进行。
public IEnumerable<DateTime> EachDay(DateTime from, DateTime thru)
{
for (var day = from.Date; day.Date <= thru.Date; day = day.AddDays(1))
yield return day;
}
public decimal PrincipalplusInterest()
{
DateTime startDate = new DateTime( DateTime.Now.Year, 1, 1);
DateTime endDate = startDate.AddYears(1);
int compoundingTimes = 12;
TimeSpan duration = endDate - startDate;
var numberOfDaysInYear = duration.Days;
decimal runningTotal = 0;
double interestRate = InterestRate;
foreach (DateTime day in EachDay(startDate, endDate))
{
decimal sumOfAnyTransactionToday = Transactions.Where(x => x.TransactionDate == day).Sum(x => x.Amount);
runningTotal = runningTotal + sumOfAnyTransactionToday;
double timePeriod = 1 / numberOfDaysInYear;
double rate = interestRate / compoundingTimes;
double total = System.Convert.ToDouble(runningTotal);
double principalAndInterest = total * Math.Pow((1 + rate), (compoundingTimes * timePeriod));
runningTotal = System.Convert.ToDecimal(principalAndInterest);
}
return runningTotal;
}
[DisplayName("Year to Date Interest")]
public decimal YrToDateInterest()
{
decimal interest = PrincipalplusInterest() - CurrentBalanceCalculation();
return interest;
}
答案 0 :(得分:0)
你在这里做整数运算:
double timePeriod = 1 / numberOfDaysInYear;
numberOfDaysInYear
是一个int,因此将1除以此值将始终返回0.
通过使其中一个值浮点来计算浮点数:
double timePeriod = 1.0 / numberOfDaysInYear;
可能是最简单的解决方案。
此外,如果您的交易包含时间组件,那么此语句将始终返回零,除非您恰好在午夜发生交易。
Transactions.Where(x => x.TransactionDate == day).Sum(x => x.Amount);
要获取您需要的日期,请获取Date
对象的DateTime
组件:
Transactions.Where(x => x.TransactionDate.Date == day).Sum(x => x.Amount);