我正在用一個非常基本的計算器腳本練習開關語句,但很困惑爲什麼我的最後一行寫出浮點變量結果正在接收錯誤: 「使用未分配的本地變量」。是的,有更好的方法來製作一個包含循環的計算器,我想下一步嘗試,但現在它是C#的寶貝步驟。下面是我的代碼,謝謝大家!基本C#計算器練習 - 「使用未分配的局部變量」錯誤
namespace Calculator
{
class Program
{
static void Main(string[] args)
{
// Greeting.
Console.WriteLine ("Welcome to the basic calculator");
// Get first value.
Console.WriteLine ("Enter the first value.");
string firstValueAsText = Console.ReadLine();
float a = Convert.ToSingle (firstValueAsText);
// Get second value.
Console.WriteLine ("Enter the second value.");
string secondValueAsText = Console.ReadLine();
float b = Convert.ToSingle (secondValueAsText);
// Prompt operation.
Console.WriteLine ("Enter '+', '-', '*', '/', '^'.");
string operation = Console.ReadLine();
// Establishing the result and error variables for later.
float result;
string error = "ERROR";
// Define switch operations.
switch (operation)
{
case "+":
result = a + b;
break;
case "-":
result = a - b;
break;
case "*":
result = a * b;
break;
case "/":
result = a/b;
break;
case "^":
result = (float)Math.Pow(a, b);
break;
default:
Console.WriteLine (error);
break;
}
// Print the result.
Console.WriteLine (a + " " + operation + " " + b + " = " + result);
Console.ReadKey();
}
}
}
看看如果用戶輸入無效操作會發生什麼。 –