C# 可变范围trought If/else If块
我有个问题。我编写了一个控制台应用程序进行练习。程序反复要求用户键入一个数字,程序将这些数字相加,当用户键入“完成”时,程序将总数除以输入的数字 所以我的问题是。该程序不会遵守,因为正如您所看到的,我必须声明int converted=int.Parse(输入);在else子句中,因为如果用户键入数字,程序将跳过前2个选项,并将字符串转换为数字,程序将继续它应该继续的操作,但是因为我声明了转换为else的int,在else if中转换的int不存在 我知道我必须把所有的东西放在同一个括号里,因为变量的作用域,但是怎么做呢C# 可变范围trought If/else If块,c#,scope,C#,Scope,我有个问题。我编写了一个控制台应用程序进行练习。程序反复要求用户键入一个数字,程序将这些数字相加,当用户键入“完成”时,程序将总数除以输入的数字 所以我的问题是。该程序不会遵守,因为正如您所看到的,我必须声明int converted=int.Parse(输入);在else子句中,因为如果用户键入数字,程序将跳过前2个选项,并将字符串转换为数字,程序将继续它应该继续的操作,但是因为我声明了转换为else的int,在else if中转换的int不存在 我知道我必须把所有的东西放在同一个括号里,因为
bool keepGoing = true;
int total = 0;
//The loop begins, repeatedly asks the user for numbers.
while (true)
{
//Asks the user for numbers .
Console.Write("Type a number:");
string input = Console.ReadLine();
// When user types in quit the program quits
if (input == "quit")
{
break;
}
// When user types "done", dividing total with converted(entered numbers).
else if (input == "done")
{
total /= converted;
Console.WriteLine(total);
continue;
}
// If user types a number, convert into integer and add total and converted together.
else
{
try
{
int converted = int.Parse(input);
total += converted;
Console.WriteLine(total);
}
// Tells the user to type again.
catch (FormatException)
{
Console.WriteLine("Invalid Input, please type again");
}
}
}
此处给出的完整代码块->
int total = 0;
int converted = 0;
//The loop begins, repeatedly asks the user for numbers.
while (true)
{
//Asks the user for numbers .
Console.Write("Type a number:");
string input = Console.ReadLine();
// When user types in quit the program quits
if (input == "quit")
{
break;
}
// When user types "done", dividing total with converted(entered numbers).
else if (input == "done")
{
total /= converted;
Console.WriteLine(total);
continue;
}
// If user types a number, convert into integer and add total and converted together.
else
{
try
{
converted = int.Parse(input);
total += converted;
Console.WriteLine(total);
}
// Tells the user to type again.
catch (FormatException)
{
Console.WriteLine("Invalid Input, please type again");
}
}
}
程序将总数除以输入的数字,似乎您的程序并没有按照您的想法进行操作。充其量它将总数除以最后输入的数字。这就是我想要的行为吗?是的,你是对的,我刚刚意识到我的错误:)我应该跟踪输入的数字,对吗?我的意思是创建另一个变量,每次用户输入一个数字时,给+1,然后将其除以总数?听起来很合理:)