2016-08-14 65 views
0

我正在用一個非常基本的計算器腳本練習開關語句,但很困惑爲什麼我的最後一行寫出浮點變量結果正在接收錯誤: 「使用未分配的本地變量」。是的,有更好的方法來製作一個包含循環的計算器,我想下一步嘗試,但現在它是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(); 
     } 
    } 
} 
+0

看看如果用戶輸入無效操作會發生什麼。 –

回答

0

如果用戶輸入無效操作,它將進入default:流程。在這種情況下,result將永遠不會被分配。

您可以通過執行解決這個問題:

float result = 0; 

或:

default: 
    Console.WriteLine (error); 
    result = 0; 
    break; 
+0

太棒了,謝謝尼古拉斯 - 有道理! – jarombra

0

你沒有初始化的變量result,它沒有被分配在所有的執行路徑。

default: 
    result = 0; 
    Console.WriteLine(error); 
    break; 
+0

謝謝你Shlomo - 有道理。 – jarombra

0

如果用戶輸入一些不尋常的,它會開始:您可以通過對其進行初始化聲明時要麼克服此編譯器錯誤:

float result = 0; 

...或者在開關的default路徑設置它到default的情況下,所以你可以通過類似的處理這個

default: 
    { 
    Console.WriteLine (error); 
    result = 0; 
    break; 
    } 
相關問題