我必须为我的 C# 类制作这个基于方法的计算器。我正在使用 Visual Studio 2010,部分任务是在用户按下 Enter 时使用“计算”按钮方法。
我以前在 VS 中做过这个,但由于某种原因,这次当我尝试输入键时它一直在叮当。
这是我的代码。我不认为它与代码有任何关系,但我不知道问题是什么,所以我提出它以防万一。
任何帮助深表感谢。谢谢!
{using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Week4Calculator
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnCalculate_Click(object sender, EventArgs e)
{
double operand1 = Convert.ToDouble(txOperand1.Text);
double operand2 = Convert.ToDouble(txtOperand2.Text);
string operation = txtOperator.Text;
double result = 0;
// Verify user input is a valid operator. If valid, run getCalculation method and
// output result to result text box. If invalid, display error message.
if (operation == "/" || operation == "*" || operation == "+" || operation == "-")
{
result = getCalculation (operand1, operand2, operation);
txtResult.Text = result.ToString();
}
else{
txtResult.Text = "ERROR";
lblError.Text = "Please enter a valid operator:\nUse: + - / *";
}
}
//Calulate 2 Operands based on input from user.
public double getCalculation(double num1, double num2, string sign)
{
double answer = 0;
switch (sign)
{
case "/":
answer = num1 / num2;
break;
case "*":
answer = num1 * num2;
break;
case "+":
answer = num1 + num2;
break;
case "-":
answer = num1 - num2;
break;
}
return answer;
}
// Clears Result text box if any new input is typed into the other 3 fields.
private void txOperand1_TextChanged(object sender, EventArgs e)
{
txtResult.Text = "";
}
private void txtOperator_TextChanged(object sender, EventArgs e)
{
txtResult.Text = "";
}
private void txtOperand2_TextChanged(object sender, EventArgs e)
{
txtResult.Text = "";
}
private void btnExit_Click(object sender, EventArgs e)
{
this.Close();
}
}