"这是在这个if语句中多次发生的错误,如何使此代码正确执行


using System;
public class HelloWorld
{
public static void Main(string[] args)
{
Console.WriteLine("please enter xhundred :");
double xhundred = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("please enter xT :");
double xT = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("please enter xzero :");
double xzero = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("please enter t :");
double T = Convert.ToDouble(Console.ReadLine());
//this is the if statement of this peace of code
if ((xhundred , xT , xzero ,T ) < 0 && (  xhundred, xT , xzero ,T ) > 100 ){
Console.WriteLine("please enter a number from 0 to 100");
}
else {
Console.WriteLine( "l" );
}
double t = ((xhundred - xT )/(xhundred - xzero ))*100;
Console.WriteLine(t);
}
}

首先,我去了微软学习网站,搜索错误代码(cs0019),我发现代码不会运行,因为c#不能转换为int, cs0019也会在减法操作符-应用于字符串时生成。加法运算符+可用于string但是在我的代码中没有布尔值,我认为问题是操作符'<'不能应用于'(double, double, double, double)'和'int'类型的操作数

不能将元组与单个int进行比较。您必须对每个参数进行单个比较:

if(xhundred < 0 || xT < 0 || xzero < 0 || T < 0 || xhundred > 100 || xT > 100 || xzero > 100 || T > 100)
{
Console.WriteLine("please enter a number from 0 to 100");
}

如果你想一次比较所有的变量,你也可以使用LINQ,它更舒适:

int[] variables = new int[] { xhundred , xT , xzero ,T };
if(variables.Any(x => x < 0 || x > 100))
{
Console.WriteLine("please enter a number from 0 to 100");
}

或者您在单个if中执行每次检查,以便用户知道哪个变量无效:

Console.WriteLine("please enter xhundred :");
double xhundred = Convert.ToDouble(Console.ReadLine());
if(xhundred < 0 || xhundred > 100)
{
Console.WriteLine("please enter a number from 0 to 100");
return;
}
Console.WriteLine("please enter xT :");
double xT = Convert.ToDouble(Console.ReadLine());
if(xT< 0 || xT > 100)
{
Console.WriteLine("please enter a number from 0 to 100");
return;
}
// and so on

你也可以将代码封装在一个方法中:

private double? ReadValue(string name, int lowerBorder, int upperBorder)
{
Console.WriteLine("please enter "+name+" :");
double value = Convert.ToDouble(Console.ReadLine());
if(value < lowerBorder || value> upperBorder)
{
Console.WriteLine("please enter a number from "+lowerBorder+" to "+upperBorder);
return null;
}
return value;
}

相关内容

  • 没有找到相关文章

最新更新