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");
}
}
}
}
'Math.Pow'需要'double'參數,而不是'decimal'。 – AlexD
另外,你在這裏用小數做了什麼?爲什麼不用「雙」呢? –
我想我想通了。我改變了這一行,它的工作原理://計算當前值 decimal presentValue =(decimal)futureValue /(decimal)Math.Pow((double)(1 + annIntRate),(double)numYears); –