返回的最常规值是什么?
本文关键字:是什么 常规值 返回 | 更新日期: 2023-09-27 18:05:22
我只是想问你:我有一个计算三角形面积的方法,有3个参数-三角形的边。该方法的返回类型是double。所以如果每两条边的和小于第三条边,我必须返回一个值。在错误的情况下返回的最常规值是什么?我建议目前double.NaN
是最佳实践。
public static double CalculateTriangleArea(double firstSide, double secondSide, double thirdSide)
{
bool areSidesPositive = (firstSide <= 0) || (secondSide <= 0) || (thirdSide <= 0);
if (areSidesPositive)
{
double halfPerimeter = (firstSide + secondSide + thirdSide) / 2;
double area = Math.Sqrt(halfPerimeter * (halfPerimeter - firstSide) * (halfPerimeter - secondSide) * (halfPerimeter - thirdSide));
return area;
}
return double.NaN;
}
您可以使用:
return default(double);
一个建议的答案是
public static bool TryCalculateTriangleArea(double firstSide, double secondSide, double thirdSide,out double rArea)
{
bool areSidesPositive = (firstSide <= 0) || (secondSide <= 0) || (thirdSide <= 0);
if (areSidesPositive)
{
double halfPerimeter = (firstSide + secondSide + thirdSide) / 2;
double area = Math.Sqrt(halfPerimeter * (halfPerimeter - firstSide) * (halfPerimeter - secondSide) * (halfPerimeter - thirdSide));
rArea= area;
return true ;
}
return false
}
你的代码是错误的,你应该有if (!areSidesPositive)
而不是if (areSidesPositive)
…即使有好的参数,你的代码也不会被执行。是的,抛出一个ArgumentException,这是继续的最好方法。
在这种情况下,您可以使用double value返回:
return default(double);
也正如Tim建议的那样,如果ArgumentException
是无效参数,则最好抛出它。
public static double CalculateTriangleArea(double firstSide, double secondSide, double thirdSide)
{
bool areSidesPositive = (firstSide <= 0) || (secondSide <= 0) || (thirdSide <= 0);
if (areSidesPositive)
{
double halfPerimeter = (firstSide + secondSide + thirdSide) / 2;
double area = Math.Sqrt(halfPerimeter * (halfPerimeter - firstSide) * (halfPerimeter - secondSide) * (halfPerimeter - thirdSide));
return area;
}
throw new ArgumentException("Argument not correct",
firstSide,secondSide, thirdSide);
}
通过传递一侧比其他两个组合更长,您违反了函数的(隐式)先决条件,因此我建议抛出ArgumentException
而不是返回值。
根据您的具体情况,不需要做任何事情:
public static double CalculateTriangleArea(double firstSide, double secondSide, double thirdSide)
{
double halfPerimeter = (firstSide + secondSide + thirdSide) / 2;
return Math.Sqrt(halfPerimeter * (halfPerimeter - firstSide) * (halfPerimeter - secondSide) * (halfPerimeter - thirdSide));
}
点是Math.Sqrt
将返回NaN
/+Infinity
如果参数是错误的(它是异常无方法)。你必须检查返回值(如果它是NaN
或+Infinity
)使用它之前。
其他可能的方法是抛出异常(ArugmentException
?ArgumentOutOfRangeException
吗?YourOwnException
吗?无论什么),以便在参数错误的情况下清楚地中断程序流程。尽管有开销,但在具有多个相互关联的操作的场景中,它可能是一种首选方法。If
更快,但是泛化错误(显示"Something is wrong"
消息)可能会更好,如果你真的不关心到底是什么错了,只是想打破流程。