c# if语句中的while循环如何在用户输入有效数据时跳出
本文关键字:有效 输入 用户 有效数 数据 语句 if while 循环 | 更新日期: 2023-09-27 18:14:27
我想知道在if语句括号中放入什么来告诉程序,如果x或y等于双精度,它可以跳出并继续执行我的其余代码。
有什么建议吗?
while (true)
{
Console.Write("I need to pour this much from this one: ");
string thisOne = Console.ReadLine();
Double.TryParse(thisOne, out x);
if ( /* Here I want to put "x is a number/double*/ )
{
break;
}
}
while (true)
{
Console.Write("I need to pour this much from that one: ");
string thatOne = Console.ReadLine();
Double.TryParse(thatOne, out y);
if (/* Here I want to put "y is a number/double*/)
{
break;
}
}
TryParse返回一个布尔值,表示解析是否成功
if (Double.TryParse(thatOne, out y))
{
break;
}
从文档返回值表示转换成功还是失败。
Double.TryParse
返回一个布尔值,非常适合您的if语句
if (Double.TryParse(thatOne, out y)) {
break;
}
您对TryParse()有误解。你想检查x是否是双精度数。在你的代码上面的某个地方,你没有把它贴在这里,可能有一行像double x = 0;
。你已经定义了x和y是double。你想检查你的输入是否可以被解析为double:
简写的版本是:
if (Double.TryParse(thatOne, out x))
{
break;
}
也可以写成:
bool isThisOneDouble = Double.TryParse(thisOne, out x);
if (isThisOneDouble)
{
break;
}
如果你真的想检查一个变量是否是某种类型而不尝试解析它,可以这样尝试:
double x = 3;
bool isXdouble = x.GetType() == typeof(double);
或
double x = 3;
if(x.GetType() == typeof(double))
{
// do something
}
根据文档,如果解析成功,TryParse返回true,因此只需将TryParse放入if语句中。
用bool控制循环,当满足条件时将bool设为false…
bool running = true;
while (running)
{
Console.Write("I need to pour this much from this one: ");
string thisOne = Console.ReadLine();
if (Double.TryParse(thisOne, out y))
{
running = false
}
}