2014-10-19 52 views
-2

SO,我已經仔細檢查了這個代碼大約10次,並且看不出它爲什麼會給我一個未分配的變量錯誤。在C#應用程序中使用「未分配的變量」

我的方法:

  private void Calculate(TextBox opOne, TextBox opTwo, TextBox txt_operation) 
    { 
     decimal operandOne = Convert.ToDecimal(opOne.Text); 
     decimal operandTwo = Convert.ToDecimal(opTwo.Text); 
     string operation = txt_operation.Text; 
     decimal result; 

     //determine and perform mathematical operation 
     if (operation == "+") 
      result = operandOne + operandTwo; 
     else if (operation == "-") 
      result = operandOne - operandTwo; 
     else if (operation == "/") 
      result = operandOne/operandTwo; 
     else if (operation == "*") 
      result = operandOne * operandTwo; 

     string formattedResult = result.ToString("F4"); //this line has the error for the result variable, but the result variable is listed in the above if/else clauses 

     //set formatted result text to text box 
     txt_Result.Text = formattedResult; 

    } 

的錯誤是在哪裏我評論

SOLUTION行:

數據是通過其他方法進行有效性檢查後,此方法被調用。因此,如果我們到了這一點,操作值是四個選項之一,*,/,+或 -

所以,簡單地說,我將上一個'else if()'語句更改爲else語句,因爲這是唯一剩下的可能性。在這一點上沒有其他可能。

   //determine and perform mathematical operation 
     if (operation == "+") 
      result = operandOne + operandTwo; 
     else if (operation == "-") 
      result = operandOne - operandTwo; 
     else if (operation == "/") 
      result = operandOne/operandTwo; 
     else 
      result = operandOne * operandTwo; 

     string formattedResult = result.ToString("F4"); 
+1

順便說一下,C#可以讓你在switch中使用字符串。 – 2014-10-19 21:39:32

+0

試着把一個'else {Response.Write(「No if statement hit」); }'如果你看到那一行,那麼你的if語句或你的參數/變量賦值有什麼問題 – Abbath 2014-10-19 21:39:34

回答

3

如果所有if小號失敗(operation是沒有的+-/*),result撐初始化。

試着這麼做:

if (operation == "+") 
    result = operandOne + operandTwo; 
else if (operation == "-") 
    result = operandOne - operandTwo; 
else if (operation == "/") 
    result = operandOne/operandTwo; 
else if (operation == "*") 
    result = operandOne * operandTwo; 
else 
    throw new Exception("Unexpected operation."); 

string formattedResult = result.ToString("F4"); 
+0

謝謝你的回答。它幫助我解決了這個問題,我將在原始問題中展示它。 – user3175451 2014-10-19 21:45:29

0

初始化結果與例如或全部否則,如果後添加其他聲明和一些值分配給結果裏面。

+0

看到我改變的問題,顯示我的解決方案 – user3175451 2014-10-19 21:48:55

+1

你的解決方案將工作,但它會處理乘法操作,除了'+','-','/'以外,所以AlexD的解決方案更好。 – Seprum 2014-10-19 21:53:04