使用C#中每个循环的新参数值调用方法

时间:2014-03-21 12:15:36

标签: c# asp.net-mvc loops

[HttpPost]
    public ActionResult ShowDetailRate(FormCollection form)
    {
        List<Calculation> finalList = new List<Calculation>();
        Calculation calc3 = new Calculation();
        double InterestRate = 0;
        double guess = 0.01;
        double guess2 = 0.03;
        for (int i = 0; i < 50; i++)
        {
            InterestRate = secantInterestRate(guess, guess2, form);
            if (radio == "inArrears")
            {
                radioCalc = 0;
            }
            else
            {
                radioCalc = InvoiceAmount;
            }
            calc3.PeriodStartDate = PeriodStartDate;
            calc3.PeriodEndDate = PeriodEndDate;
            if (DTC == "365/365")
            {
                calc3.NumberOfDays = Convert.ToInt32((calc3.PeriodEndDate - calc3.PeriodStartDate).Days) + 1;
            }
            else if (DTC == "360/360")
            {
                calc3.NumberOfDays = 30;
            }
            calc3.InvoiceAmount = InvoiceAmount;
            calc3.InterestRate = InterestRate;
            calc3.InterestAmount = (PV - radioCalc) * InterestRate / DTCyear * calc3.NumberOfDays;
            calc3.Amortization = (calc3.InvoiceAmount - calc3.InterestAmount);
            calc3.PresentValue = PV - calc3.Amortization;
            calc3.StartValue = PV;
            finalList.Add(calc3);
            var count = finalList.Count();
            if (finalList[count].PresentValue != FV)
            {
                guess = guess2;
                guess2 = calc3.InterestRate;
                continue;
            }
            else
                break;
        }
        return PartialView("ShowDetail", finalList);
    }

在上面的方法中,我使用我的变量InterestRate来调用名为secantInterestRate的方法,其中包含3个参数(doubledouble,{{1} })。循环的第一轮我希望前两个参数设置为(0.01,0.03),但在第二轮循环中我想要FormCollectionguess = guess 2。并且仍然在循环开始时调用方法guess2 = calc3.InterestRate但是使用新值。我最后尝试了一个小的if:

secantInterestRate

但这不起作用,因为当循环开始时var count = finalList.Count() - 3; if (finalList[count].PresentValue != FV) { guess = guess2; guess2 = calc3.InterestRate; continue; } else break; 将为0.01,而guess将再次为0.03,而不是我想要它。

是否可以为循环中的每个新回合设置guess2guess = guess2

2 个答案:

答案 0 :(得分:0)

这样的事情?

if (i==0) { 
  guess = guess2;
  guess2 = calc3.InterestRate;
} else { 
  // you don't want to change the values after the first time through; do nothing
} 

PS:我建议您从表单处理代码中分解计算代码,或以其他方式使该方法更具可读性。目前很难看到逻辑,因为有如此多的代码行,这可能是解决像这样的小问题很难解决的主要原因。

答案 1 :(得分:0)

根据以下内容更改您的代码:

....
for (int i = 0; i < 50; i++)
{
    if (i > 0)
    {
          guess = guess2;
          guess2 = calc3.InterestRate;
    }
    InterestRate = secantInterestRate(guess, guess2, form);
...