允许只输入一个数字 - C#

The*_*heQ 0 c# console numbers

我对C#很新.我正在尝试制作一个将摄氏度转换为华氏度的基本程序.但是这里有捕获,我想确保用户只输入有效数字而不输入字符或符号.如果用户输入,例如39a,23,则控制台要求他再次输入该号码.

 Console.WriteLine("Please enter the temperature in Celsius: ");
 double x = Convert.ToDouble(Console.ReadLine());
Run Code Online (Sandbox Code Playgroud)

另外,我一直在制作其他程序,我一直在想 - 我是否总是要使用"Convert.ToInt/Convert.ToDouble"?还是有更快的方法?

Chr*_*tos 5

你使用这种方法会更好Double.TryParse.这样,您将检查用户提供的字符串是否可以解析为double.

// This is the variable, in which will be stored the temperature.
double temperature;

// Ask the  user input the temperature.
Console.WriteLine("Please enter the temperature in Celsius: ");

// If the given temperature hasn't the right format, 
// ask the user to input it again.
while(!Double.TryParse(Console.ReadLine(), out temperature))
{
    Console.WriteLine("The temperature has not the right format, please enter again the temperature: ");
}
Run Code Online (Sandbox Code Playgroud)

如果解析成功并且不是,则该方法Double.TryParse(inputString, out temperature)将返回.truefalse

有关该方法的更多信息,Double.TryParse请查看此处.