主要方法
private void btnCalculate_Click(object sender, EventArgs e)
{
if (this.txtFirst.Text==""||this.txtSecond.Text==""||this.cboOperator.Text=="")
{
MessageBox.Show("操作数或运算符不能为空","操作提示",MessageBoxButtons.OK,MessageBoxIcon.Warning);
return;
}
double firstNum = double.Parse(this.txtFirst.Text);
double secondNum = double.Parse(this.txtSecond.Text);
string operate = this.cboOperator.Text;
if (secondNum == 0 && operate == "/")
{
MessageBox.Show("除数不能为0,请重新输入!", "操作提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
this.txtResult.Text = Calculate(firstNum, secondNum, operate).ToString();
}
} public double Calculate(double firstNum, double secondNum, string operate)
{
if (operate == "+")
{
return firstNum + secondNum;
}
else if (operate == "-")
{
return firstNum - secondNum;
}
else if (operate == "*")
{
return firstNum * secondNum;
}
else
{
return firstNum / secondNum;
}
}
当输入5.05 - 5 时结果是0.0499999999999998 ,而不是5.00感兴趣的朋友也可以到 http://download.csdn.net/source/2516203 下载来看看,谢谢大家
{
if (this.txtFirst.Text==""||this.txtSecond.Text==""||this.cboOperator.Text=="")
{
MessageBox.Show("操作数或运算符不能为空","操作提示",MessageBoxButtons.OK,MessageBoxIcon.Warning);
return;
}
decimal firstNum = decimal.Parse(this.txtFirst.Text);
decimal secondNum = decimal.Parse(this.txtSecond.Text);
string operate = this.cboOperator.Text;
if (secondNum == 0 && operate == "/")
{
MessageBox.Show("除数不能为0,请重新输入!", "操作提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
this.txtResult.Text = Calculate(firstNum, secondNum, operate).ToString();
}
} public decimal Calculate(decimal firstNum, decimal secondNum, string operate)
{
if (operate == "+")
{
return firstNum + secondNum;
}
else if (operate == "-")
{
return firstNum - secondNum;
}
else if (operate == "*")
{
return firstNum * secondNum;
}
else
{
return firstNum / secondNum;
}
}
就如比较double类型是否为0一样,要允许一定的误差
if(Math.Abs(dblValue)<0.000001)
{
MessageBox.Show("dblValue=0");
}
else
{
MessageBox.Show("dblValue!=0");}