下面的代码运行一个'for'循环来创建第1个月到第12个月,然后根据它们的编号命名每个月Jan到Dec。那几篇汇编得很好。在底部,我试图在屏幕上写下月份名称的地方是它失败的地方。上面写着"使用未分配的本地变量‘monthName’;然而monthName之前刚刚使用过,并在上面声明。如果您能提供任何帮助,我们将不胜感激。
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
永远不会被赋值,这就是编译器所抱怨的。要修复它,只需在声明变量时初始化它:
string monthName = null;
此外,您的代码也有一些可疑之处,因为monthName
是在声明它的循环之外使用的,但我认为这是一个拼写错误,因为现在的代码不会给您带来您所询问的错误。
您已经在For循环的范围下声明了monthName、monthlyProd和monthlySales,并试图在For循环范围之外使用这些变量。您应该在循环之前声明变量-
string monthName;
double monthlyProd = .1 * dProdRate;
double monthlySales = .07 * dSalesRate;
for (int month = 1; month <= 12; month++)
{
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);