【发布时间】:2026-02-15 02:15:02
【问题描述】:
C# 新手(目前只编码一周)试图创建一个练习程序。似乎无法获得我想要存储在“price1”和“price2”中的数据。错误是 CS0165 使用未分配的局部变量“price1”和“price2”。
我试过移动代码行并添加一个返回命令,但我似乎不太明白。
Console.Write("What grocery are you buying: ");
string product1 = Console.ReadLine();
Console.Write("How many are you buying: ");
int quantity1 = Convert.ToInt32(Console.ReadLine());
double price1;
if (product1 == "Steak")
{
price1 = Convert.ToDouble(steak.price * quantity1);
}
if (product1 == "Cheerios")
{
price1 = Convert.ToDouble(cheerios.price * quantity1);
}
if (product1 == "Pepsi")
{
price1 = Convert.ToDouble(pepsi.price * quantity1);
}
if (product1 == "Celeste Pizza")
{
price1 = Convert.ToDouble(celeste.price * quantity1);
}
Console.Write("What second grocery are you buying: ");
string product2 = Console.ReadLine();
Console.Write("How many are you buying: ");
int quantity2 = Convert.ToInt32(Console.ReadLine());
double price2;
if (product2 == "Steak")
{
price2 = Convert.ToDouble(steak.price * quantity2);
}
if (product1 == "Cheerios")
{
price2 = Convert.ToDouble(cheerios.price * quantity2);
}
if (product1 == "Pepsi")
{
price2 = Convert.ToDouble(pepsi.price * quantity2);
}
if (product1 == "Celeste Pizza")
{
price2 = Convert.ToDouble(celeste.price * quantity2);
}
Console.WriteLine(price1 + price2);
尝试获取存储在“price1”和“price2”中的数据,以便最后将它们加在一起。抱歉,如果我在这里弄错了任何术语。
【问题讨论】:
-
当代码到达
What second grocery are you buying行时,是否保证 将值分配给price1?您有四个if语句可能会分配一个值,但是这四个条件是否可能都不匹配?这就是您收到此错误的原因。在变量被赋予值之前,您不能使用该变量的值。 -
如果您包含整个 .cs 文件以节省时间会很有帮助。
-
仅供参考,将我是初学者等放在您的问题中将永远不会有帮助。我们不关心您的知识水平,我们只关心他们是否措辞得当、经过深思熟虑、格式化,而不是重复