我遇到了一个问题,即计算方法不断返回结果的默认值,而该方法似乎无法读取表单中的运算符输入。
有人知道我做错了吗?
这是我的代码:
namespace Prac5
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnCalculate_Click(object sender, EventArgs e)
{
try
{
decimal Operand1 = Convert.ToDecimal(txtOperand1.Text);
decimal Operand2 = Convert.ToDecimal(txtOperand2.Text);
string Operator = Convert.ToString(txtOperator);
if ((Operand1 <= 1000000 && Operand1 >= 1) && (Operand2 <= 1000000 && Operand2 >= 1))
{
decimal Result = Calculation(Operand1, Operand2, Operator);
Result = Math.Round(Result, 4);
txtResult.Text = Result.ToString();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + "\n\n" +
ex.GetType().ToString() + "\n" +
ex.StackTrace, "Exception");
}
}
private decimal Calculation(decimal Operand1, decimal Operand2, string Operator)
{
decimal Result = 0;
switch (Operator = Convert.ToString(txtOperator))
{
case "+":
return Result = Operand1 + Operand2;
case "-":
return Result = Operand1 - Operand2;
case "*":
return Result = Operand1 * Operand2;
case "/":
return Result = Operand1 / Operand2;
default:
return Result;
}
}
private void btnExit_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
答案 0 :(得分:1)
当操作员离开文本框时,您正在尝试将文本框转换为字符串而不是文本。
string Operator = Convert.ToString(txtOperator);
应该是
string Operator = txtOperator.Text;