只允许输入数字-C# [英] Allow To Only Input A Number - C#

查看:46
本文介绍了只允许输入数字-C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对C#相当陌生.我正在尝试制作一个将摄氏度转换为华氏度的基本程序.但是要注意的是,我想确保用户仅输入有效数字,而不能输入字符或符号.并且,如果用户输入了39a,23之类的内容,则控制台会要求他再次输入该号码.

I'm fairly new to C#. I'm trying to make a basic program that converts Degrees in Celsius to Fahrenheit. But here's the catch, I want to make sure that the user inputs only a valid number and no characters or symbols. And if the user inputs, for example 39a,23, the Console asks him to enter the number again.

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

此外,我一直在开发其他程序,我一直在想-我是否总是必须使用"Convert.ToInt/Convert.ToDouble"?还是有更快的方法?

Also, I've been making other programs, and I've been wondering - do I always have to use "Convert.ToInt/Convert.ToDouble"? or is there a faster way?

推荐答案

最好使用方法 Double.TryParse .这样,您将检查用户提供的字符串是否可以解析为双精度型.

It would be better you use the method Double.TryParse. This way you will check if the string that user provided can be parsed to a 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: ");
}

如果解析成功,方法 Double.TryParse(inputString,超出温度)将返回 true ,否则返回 false .t.

The method Double.TryParse(inputString, out temperature) will return true , if the parsing is successful and false if it isn't.

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

For more information about the method Double.TryParse please have a look here.

这篇关于只允许输入数字-C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆