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");
順便說一下,C#可以讓你在switch中使用字符串。 – 2014-10-19 21:39:32
試着把一個'else {Response.Write(「No if statement hit」); }'如果你看到那一行,那麼你的if語句或你的參數/變量賦值有什麼問題 – Abbath 2014-10-19 21:39:34