我有问题。我为练习写了一个控制台应用程序。程序反复要求用户输入一个数字,程序将数字加在一起,当用户输入“完成”时,程序将总数除以输入的数字。
所以我的问题是。该程序不符合,因为你看到我必须声明int converted = int.Parse(输入);进入else子句,因为如果用户键入数字,程序将跳过前两个选项并将字符串转换为数字,程序继续应该,但因为我声明int转换为else,转换为else如果,不存在。
我知道由于范围可变,我必须将所有内容放在同一个括号中,但是如何?
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");
}
}
}
答案 0 :(得分:0)
此处给出的完整代码块 - >
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");
}
}
}