问题描述
下面的代码运行一个"for"循环,以创建第1到12个月,然后根据其编号命名从1月到12月的每个月.那块编译很好.我尝试在屏幕上写下月份名称的底部是失败的地方.它说:使用未分配的局部变量'monthName';但是,monthName以前只是使用过,并在上面声明.您能提供的任何帮助将不胜感激.
The below code runs a 'for' loop to create months 1 through 12 then names each month Jan through Dec according to their number. That pieces compiles fine. At the bottom where I try to write the month name on the screen is where it is failing. It says "use of unassigned local variable 'monthName'; however monthName was just used previously and is declared above. Any help you could provide would be greatly appreciated.
for (int month = 1; month <= 12; month++)
{
string monthName;
double monthlyProd = .1 * dProdRate;
double monthlySales = .07 * dSalesRate;
if (month == 1) { monthName = "Jan"; }
if (month == 2) { monthName = "Feb"; monthlyProd = 0; }
if (month == 3) { monthName = "Mar"; }
if (month == 4) { monthName = "Apr"; }
if (month == 5) { monthName = "May"; }
if (month == 6) { monthName = "Jun"; monthlyProd = 0; }
if (month == 7) { monthName = "Jul"; }
if (month == 8) { monthName = "Aug"; }
if (month == 9) { monthName = "Sep"; monthlySales = (.15 * dSalesRate); }
if (month == 10) { monthName = "Oct"; }
if (month == 11) { monthName = "Nov"; }
if (month == 22) { monthName = "Dec"; monthlySales = (.15 * dSalesRate); }
}
dEndingInventory += dPreviousProd - dPreviousSales;
Console.WriteLine("{0}{1,15}{2,15}{3,15}", monthName, monthlyProd, monthlySales, dEndingInventory);
推荐答案
您知道month
只能采用1到12之间的值,但编译器并不那么聪明.如果说month
为0,则永远不会为变量monthName
分配值,这就是编译器所抱怨的.要修复它,只需在声明它时初始化变量即可:
You know that month
can only take the values 1 to 12 inclusive but the compiler is not that smart. If say month
is 0 then the variable monthName
is never assigned a value and that is what the compiler is complaining about. To fix it simply initialize the variable when you declare it:
string monthName = null;
此外,您的代码有些混乱,因为monthName
在声明它的循环之外使用,但我认为这是一个错字,因为现在的代码不会给您您要询问的错误
Also, there is something fishy about your code because monthName
is used outside the loop where it is declared but I assume that this is a typo because the code as it stands now will not give you the error you are asking about.
这篇关于使用已分配的未分配局部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!