2015-07-19 21 views
0

我正在尝试将X天数的便士数量加倍。付出的便士 - 数学计算 - C#

因此,3天= 4个便士,4天= 8个便士,等

我卡上得到正确的代码放在:(我知道我很接近,我知道我失去了一些东西我已经花了5个小时在这,我只是想看到解决方案,所以我的头脑会把它放在一起,它是如何工作的...)

我终于明白了...现在...怎么可以我清理了这个?我还在学习中较少的代码写的...但我正在关注的起步W/Visual C#中的书现在...

  // Local variables./
      int daysWorkedInputValue; 
      decimal currentPayRate, newPayRate, totalPaySalary; 

      int daysWorked; 
      int count = 0; 
      currentPayRate = 0.01m; 
      totalPaySalary = 0m; 

      daysWorkedInputValue = int.Parse(daysWorkedInputTextBox.Text); 

      if (int.TryParse(daysWorkedInputTextBox.Text, out daysWorked)) 
      { 
       if (daysWorked >= 0) 
       { 
        // Continue to process the input./

        if (daysWorkedInputValue == 0) 
        { 
         totalPayCalcLabel.Text = "$0.00"; 
        } 

        if (daysWorkedInputValue == 1) 
        { 
         totalPayCalcLabel.Text = "$0.01"; 
        } 

        // The following loop calculates the total pay./
        while (count <= (daysWorked - 1)) 
        { 
         // Calculate the total pay amount./
         if (count == 1) 
         { 
          currentPayRate = 0.01m; 
          totalPayCalcLabel.Text = currentPayRate.ToString("c"); 
         } 

         currentPayRate = currentPayRate * 2; 
         totalPaySalary = currentPayRate; 

         if (count >= 1) 
         { 
          totalPayCalcLabel.Text = totalPaySalary.ToString("c"); 
         } 

         // Add one to the loop counter./
         count = count + 1; 

         // Return focus back to the organisms TextBox./
         daysWorkedInputTextBox.Focus(); 

        } 
+0

看起来是GP,它是几何级数(https://en.wikipedia.org/wiki/Geometric_progression)? – Agalo

+1

请分享问题背景的完整代码。你没有增加计数,还有其他的东西(没有休息,没有currentPay的重新分配) – Typist

回答

5

我看到一个很明显的模式在这里:

3 days -> 2^(3-1) = 4 pennies 
4 days -> 2^(4-1) = 8 pennies 

所以,你要解决的方程式:

pennies = 2^(days-1) 

我还没有运行您的代码,看看有什么是错的(什么也没有改变countdaysWorked的价值,所以我假设你最终会被卡住在...中无限循环),但这应该工作得很好:

var pennies = Math.Pow(2, days - 1);