2016-09-17 31 views
0

我想在C#中做一个基本的程序来计算netPay和grossPay,但是我遇到了一个小问题。在将交换机添加到我的程序后,我添加了一个开关,将我的taxRate设置为基于提供的字母的常量,它表示taxRate是未分配的本地变量。我对C#仍然很陌生,所以我可能犯了一个非常简单的错误,但是对于我来说,我无法找到它。先谢谢您的帮助。C#使用未分配的本地变量

 const int married = 15, single = 22, divorced = 23, widowed = 13; 
     double payRate, hoursWorked, grossPay, netPay; 
     double taxRate; 
     char marStatus; 



     Console.WriteLine("Please Enter Hourly Wages"); 
     payRate = int.Parse(Console.ReadLine()); 

     Console.WriteLine("Please Enter Hours Worked"); 
     hoursWorked = int.Parse(Console.ReadLine()); 

     Console.WriteLine("Please Enter Marital Status Letter: (M) Married (S) Single (D) Divorced (W) Widowed"); 
     marStatus =Convert.ToChar(Console.ReadLine()); 


     switch (marStatus) 
     { 
      case 'M': 
       taxRate = married; 
       break; 
      case 'S': 
       taxRate = single; 
       break; 
      case 'D': 
       taxRate = divorced; 
       break; 
      case 'W': 
       taxRate = widowed; 
       break; 
      default: 
       Console.WriteLine("Invalid Input, Please Try Again."); 
       break; 
     } 

     if (hoursWorked > 40) 
     {grossPay =((hoursWorked-40)*(payRate*1.5))+(40*payRate);} 
     else 
     { grossPay = payRate * hoursWorked; } 

     netPay = grossPay * taxRate; // This is where I have the problem 

     Console.WriteLine("Gross Pay=" +grossPay); 
     Console.WriteLine("Net Pay=" +netPay); 
     Console.WriteLine("xxx"); 

     Console.ReadLine(); 

回答

1
中的switch-case

,如果defual情况下得到满足(没有其他情况下匹配 “marStatus”),然后TAXRATE没有得到一个值asigned。之后你尝试使用这个变量,没有任何价值。这是你得到的编译错误。为变量赋值。