2017-09-22 36 views
-1

我正在做這個計算器使用System.Windows.Forms,每次我嘗試做一個平方根,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(); 
} 

我會很感激的任何幫幫我。

編輯:唯一的例外是在trown:num2 = double.Parse(textBoxResult.Text);

+0

什麼是調試器告訴你什麼時候在'SqrtButtonClick'中設置斷點?該值是否適合傳遞給'double.Parse'? 當您檢查'resultValue'時,在''sqrt''的'case'中怎麼辦?是什麼值適合傳遞給函數'sqrt'? –

+0

現在你有你的答案。 *輸入字符串無效* –

+0

它沒有到達下一行。它停在'num2 = double.Parse(textBoxResult.Text);'但是如果我把斷點放在'case'中,它就會輸入case。 –

回答

3

要去猜,當你嘗試測試那些傢伙,在textBoxResult是空的。請注意,您正在執行該行num2 = double.Parse(textBoxResult.Text);如果最近清除了textBoxResult,那麼表單System.FormatException : Input string was not in a correct format(空字符串/ null不會被double.Parse解析爲0.00)會產生問題

+0

謝謝你,我從Sqrt,Cos,Sin和Tan刪除了'textBoxResult.Clear()',它工作正常!我感謝您的幫助。 –

+0

我在想,誰低估了這個答案! –

+0

我沒有投票,但我會猜測,投票將是由於這一事實,這解釋了*爲什麼*錯誤發生,但不是*如何防止它*(即一些討論'double.TryParse( )'和/或首先驗證'Text'屬性)。 –