2017-02-06 82 views
0

我不太确定为什么我在我的calcButton事件处理程序中的1 + annIntRate和numYears变量中出现错误。我得到的两个变量的错误是“无法从小数双转换”,但都应该是小数。请帮忙。C#语法错误 -

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Windows.Forms; 

namespace Present_Value 
{ 
    public partial class Form1 : Form 
    { 

     public Form1() 
     { 
      InitializeComponent(); 
     } 

     // Using the InputIsValid method to convert the users input and stores 
     // it in the arguments (passed by reference). If the conversion 
     // is successful, the method returns true. Otherwise it returns false. 
     private bool InputIsValid(ref decimal futureValue, ref decimal annIntRate, ref decimal numYears) 
     { 
      // Flag variable to indicate whether the input is good 
      bool inputGood = false; 

      // Try to convert all inputs to decimal. 
      if (decimal.TryParse(futureAmtTextBox.Text, out futureValue)) 
      { 
       if (decimal.TryParse(yearsTextBox.Text, out numYears)) 
       { 
        if (decimal.TryParse(rateTextBox.Text, out annIntRate)) 
        { 
         //All inputs are good. 
         inputGood = true; 
        } 
        else 
        { 
         // Display an error message for anIntRate 
         MessageBox.Show("Annual Interest Rate is invalid."); 
        } 
       } 
       else 
       { 
        // Display an error message for the numYears 
        MessageBox.Show("Years in Savings is invalid."); 
       } 
      } 
      else 
      { 
       // Dislay an error message for future value 
       MessageBox.Show("Future amount is invalid"); 
      } 
      // Return the reulst. 
      return inputGood; 
     } 



     private void calcButton_Click(object sender, EventArgs e) 
     { 
      // Variables for for the present, future value, 
      // annual interest rate, and number of years 
      decimal futureValue = 0m, annIntRate = 0m, numYears = 0m; 

      if (InputIsValid(ref futureValue, ref annIntRate, ref numYears)) 
      { 
       // Calculate Present Value 
       decimal presentValue = (decimal)futureValue/(decimal)Math.Pow((**1 + annIntRate**), **numYears**); 

       presentValLabel.Text = presentValue.ToString("C"); 
      } 


     } 
    } 
} 
+2

'Math.Pow'需要'double'参数,而不是'decimal'。 – AlexD

+0

另外,你在这里用小数做了什么?为什么不用“双”呢? –

+0

我想我想通了。我改变了这一行,它的工作原理://计算当前值 decimal presentValue =(decimal)futureValue /(decimal)Math.Pow((double)(1 + annIntRate),(double)numYears); –

回答

0

这可能会为你

decimal presentValue = (decimal) futureValue/(decimal) Math.Pow((double) (1 + annIntRate), (double) numYears); 

因为Math.Pow注意到(双人间,双人间),其回报,返回以指定功率指定数量的伎俩。