简体   繁体   English

在 C# 中检查输入是否为正确的数据类型

[英]Checking if input is correct data type in C#

What I would like is to basically have the user enter in a float, and then the system check that the input is indeed a float, and if it is then it will proceed with the code, and if it is not then the user will have to re-input the with the correct data type.我想要的是基本上让用户输入一个浮点数,然后系统检查输入是否确实是一个浮点数,如果是,则继续执行代码,如果不是,则用户将有重新输入正确的数据类型。 Sorry for the beginners question, an example of the code is:抱歉初学者的问题,代码示例如下:

            Console.Write("Response Value > ");
            Response = float.Parse(Console.ReadLine())

            Ask_Count = Ask_Count + 1;
            if (Response > 0 && Response < 6)
            {
                Valid_Count = Valid_Count + 1;
            }

How would I go about the program checking to see if Response is a float?我将如何进行程序检查以查看 Response 是否为浮点数?

Thank you.谢谢你。

Use float.TryParse for it.使用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");

another is by using is float .另一个是使用is float

bool result = varName is float;

or或者

float x = 0;
bool result = float.tryParse(varname, out x);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM