[英]Checking if input is correct data type in C#
我想要的是基本上让用户输入一个浮点数,然后系统检查输入是否确实是一个浮点数,如果是,则继续执行代码,如果不是,则用户将有重新输入正确的数据类型。 抱歉初学者的问题,代码示例如下:
Console.Write("Response Value > ");
Response = float.Parse(Console.ReadLine())
Ask_Count = Ask_Count + 1;
if (Response > 0 && Response < 6)
{
Valid_Count = Valid_Count + 1;
}
我将如何进行程序检查以查看 Response 是否为浮点数?
谢谢你。
使用float.TryParse
为它。
Console.Write("Response Value > ");
if(float.TryParse(Console.ReadLine(), out Response)
{
Ask_Count = Ask_Count + 1;
if (Response > 0 && Response < 6)
Valid_Count = Valid_Count + 1;
}
else
Console.WriteLine("Number entered is not a float");
另一个是使用is float
。
bool result = varName is float;
或者
float x = 0;
bool result = float.tryParse(varname, out x);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.