gpt4 book ai didi

在循环外声明的 C# 变量在循环中被赋值但得到 'Unassigned' 编译错误

转载 作者:行者123 更新时间:2023-11-30 17:07:13 25 4
gpt4 key购买 nike

我正在处理类作业,但无法编译。对于 multiplierStringMultiplcandString,我不断收到 “Use of unassigned local variable”。它们在 main 的顶部声明,但它似乎没有在 while 循环内为它们赋值。如果我在循环外强制一个值,错误就会消失。非常感激任何的帮助。谢谢。

这是怎么回事?

static void Main()
{

bool goodInput = false;
ConsoleKeyInfo cki;
string multiplicandString;
string multiplierString;
string endProduct;
string prompt;
string response;
Int64 TryNumber;

prompt = "This program will multiply two numbers of reasonable length.";
Console.WriteLine(prompt);
Console.WriteLine();
prompt = "Press the Escape (Esc) key to quit or any other key to continue.";
cki = Console.ReadKey();

if (cki.Key != ConsoleKey.Escape)
{
while (!goodInput)
{
prompt = "Please provide the multiplicand: ";
Console.WriteLine(prompt);
response = Console.ReadLine();

if (Int64.TryParse(response, out TryNumber))
{
goodInput = true;
multiplicandString = "a"; //TryNumber.ToString();
}
else
{
Console.WriteLine();
prompt = "Invalid multiplicand entry. It must be all numbers.\a";
Console.WriteLine(prompt);
prompt = "Please try again.";
Console.WriteLine(prompt);
} // end if Int64.TryParse
} // end while ! goodInput

goodInput = false;

while (!goodInput)
{
prompt = "Please provide the multiplier: ";
Console.WriteLine(prompt);
response = Console.ReadLine();

if (Int64.TryParse(response, out TryNumber))
{
goodInput = true;
multiplierString = "a"; //TryNumber.ToString();
}
else
{
Console.WriteLine();
prompt = "Invalid multiplier entry. It must be all numbers.\a";
Console.WriteLine(prompt);
prompt = "Please try again.";
Console.WriteLine(prompt);
} // end if Int64.TryParse
} // end while ! goodInput
//multiplierString = "a"; //TryNumber.ToString();

endProduct = MultiplyByRectangle(multiplicandString, multiplierString);

Console.WriteLine("The result of the calculation is:");
Console.WriteLine("\t" + endProduct);

} // end Main()

最佳答案

C# 需要明确分配变量。意思是,变量必须先设置一个初始值,然后才能读取它。

关于在循环外声明的 C# 变量在循环中被赋值但得到 'Unassigned' 编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14744843/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com