如何找到最高和最低数C# [英] How to find the highest and the lowest number C#
问题描述
我从三个变量的三个值。如何检查谁是最高的数字,谁是最低的数字?
I get three values from three variables. How can i check who is the highest number and who is the lowest number?
该数字表示如下:
private int _score1;
private int _score2;
private int _score2;
代码:
Code:
Public int Highest
{
return the highest number here;
}
public int Lowest
{
return the lowest number here;
}
我可以计算出我的构造函数中的最高和最低是多少?
Can i calculate the highest and the lowest number in my constructor?
推荐答案
强制性的Linq答案:
The obligatory Linq answer:
Public int Highest(params int[] inputs)
{
return inputs.Max();
}
public int Lowest(params int[] inputs)
{
return inputs.Min();
}
这一块的美妙之处在于它可以采取任何数量的整数输入。为了使故障安全,你应该检查空/空输入阵列(也就是说没有被传递到方法)。
The beauty of this one is that it can take any number of integer inputs. To make it fail-safe you should check for a null/empty inputs array (meaning nothing was passed into the method).
要做到这一点没有LINQ中,你基本上只是有模仿的扩展方法执行的逻辑:
To do this without Linq, you basically just have to mimic the logic performed by the extension method:
Public int Lowest(params int[] inputs)
{
int lowest = inputs[0];
foreach(var input in inputs)
if(input < lowest) lowest = input;
return lowest;
}
再次使它万无一失,你应该检查空或NULL输入数组,因为调用最低()将抛出一个ArrayIndexOutOfBoundsException。
Again, to make it foolproof you should check for an empty or null inputs array, because calling Lowest() will throw an ArrayIndexOutOfBoundsException.
这篇关于如何找到最高和最低数C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!