【发布时间】:2019-03-12 17:14:46
【问题描述】:
我正在尝试向此代码添加一个 Try/Catch 块,但我不知道要更改什么才能使其正常工作..
有什么建议吗? 收到此错误:
“错误 CS0103 名称‘华氏’在当前上下文中不存在”
class Program
{
static int FahrenheitToCelsius(int fahrenheit)
{
int celsius = ((fahrenheit - 32) * 5) / 9;
return celsius;
}
static void Main(string[] args)
{
int celsius;
Console.WriteLine("Hello! Welcome to the sauna!");
Console.WriteLine();
Console.WriteLine("Please enter your desired degrees in Fahrenheit: ");
do
{
try
{
int fahrenheit = Convert.ToInt32(Console.ReadLine());
}
catch (FormatException)
{
}
celsius = FahrenheitToCelsius(fahrenheit);
Console.WriteLine("The sauna is now set to " + fahrenheit +
" degrees Fahrenheit, which equals to " + celsius + " degrees Celsius.");
if (celsius < 25)
{
Console.WriteLine("Way too cold! Turn the heat up: ");
}
else if (celsius < 50)
{
Console.WriteLine("Too cold, turn the heat up: ");
}
else if (celsius < 73)
{
Console.WriteLine("Just a little bit too cold, turn the heat up a " +
"little to reach the optimal temperature: ");
}
else if (celsius == 75)
{
Console.WriteLine("The optimal temperature has been reached!");
}
else if (celsius > 77)
{
Console.WriteLine("Too hot! Turn the heat down: ");
}
else
Console.WriteLine("The sauna is ready!");
{
}
} while (celsius < 73 || 77 < celsius);
Console.ReadLine();
}
}
【问题讨论】:
-
如果您想在该块之外访问它,只需在
farenheit块的范围之外定义farenheit。也许你在哪里定义celcius? -
话虽如此,您应该真正使用
int.TryParse而不是异常处理来验证用户输入。