为什么这个计算器给我'输入字符串格式不正确'错误?

时间:2017-09-22 23:24:29

标签: c# .net winforms exception calculator

我正在使用System.Windows.Forms做这个计算器,每当我尝试做Square Root,Cos,Sin或Tan操作并点击Equals按钮时它会停止并告诉我'System.FormatException:输入字符串不是以正确的格式'我不知道为什么。

这是我的buttonEquals_Click事件:

private void buttonEquals_Click(object sender, EventArgs e)
{
    double num2;
    double answer;

    num2 = double.Parse(textBoxResult.Text);

    switch (theOperator)
    {
        case "+":
            answer = resultValue + num2;
            textBoxResult.Text = answer.ToString();
            resultValue = 0;
            break;
        case "-":
            answer = resultValue - num2;
            textBoxResult.Text = answer.ToString();
            resultValue = 0;
            break;
        case "×":
            answer = resultValue * num2;
            textBoxResult.Text = answer.ToString();
            resultValue = 0;
            break;
        case "÷":
            answer = resultValue / num2;
            textBoxResult.Text = answer.ToString();
            resultValue = 0;
            break;
        case "sqrt":
            answer = Math.Sqrt(resultValue);
            textBoxResult.Text = answer.ToString();
            resultValue = 0;
            break;
        case "exp":
            answer = Math.Pow(resultValue, num2);
            textBoxResult.Text = answer.ToString();
            resultValue = 0;
            break;
        case "sin":
            answer = Math.Sin(resultValue);
            textBoxResult.Text = answer.ToString();
            resultValue = 0;
            break;
        case "cos":
            answer = Math.Cos(resultValue);
            textBoxResult.Text = answer.ToString();
            resultValue = 0;
            break;
        case "tan":
            answer = Math.Tan(resultValue); 
            textBoxResult.Text = answer.ToString();
            resultValue = 0;
            break;
        default:
            answer = 0;
            break;
    }
}

这是我的SqrtButton_Click事件和DivisionButton_event(所以你可以看到它与DivisionButton一起工作):

private void SqrtButton_Click(object sender, EventArgs e)
{
    resultValue = resultValue + double.Parse(textBoxResult.Text);
    theOperator = "sqrt";
    textBoxResult.Clear();
}

private void DivisionButton_Click(object sender, EventArgs e)
{
    resultValue = resultValue + double.Parse(textBoxResult.Text);
    theOperator = "÷";
    textBoxResult.Clear();
}

我很感激任何帮助。

编辑:例外情况是:num2 = double.Parse(textBoxResult.Text);

1 个答案:

答案 0 :(得分:3)

猜测当你试图测试那些人时,textBoxResult是空的。请注意,您正在执行第num2 = double.Parse(textBoxResult.Text);行如果最近清除了textBoxResult,那么您将遇到System.FormatException : Input string was not in a correct format形式的问题(空字符串/ null不会被double.Parse解析作为0.00)