在C#中,有没有一种方法可以找到最多3个数字?


Answers:


142

好吧,您可以调用它两次:

int max3 = Math.Max(x, Math.Max(y, z));

如果您发现自己在做很多事情,则可以总是编写自己的帮助程序方法...我很高兴在我的代码库中看到过一次,但并不定期。

(请注意,这可能比安德鲁基于LINQ的答案更有效-但显然,您拥有的元素越多,LINQ方法就越具有吸引力。)

编辑:“两全其美”的方法可能是采用以下两种方法之一来定制一组方法:

public static class MoreMath
{
    // This method only exists for consistency, so you can *always* call
    // MoreMath.Max instead of alternating between MoreMath.Max and Math.Max
    // depending on your argument count.
    public static int Max(int x, int y)
    {
        return Math.Max(x, y);
    }

    public static int Max(int x, int y, int z)
    {
        // Or inline it as x < y ? (y < z ? z : y) : (x < z ? z : x);
        // Time it before micro-optimizing though!
        return Math.Max(x, Math.Max(y, z));
    }

    public static int Max(int w, int x, int y, int z)
    {
        return Math.Max(w, Math.Max(x, Math.Max(y, z)));
    }

    public static int Max(params int[] values)
    {
        return Enumerable.Max(values);
    }
}

这样,您可以编写MoreMath.Max(1, 2, 3)MoreMath.Max(1, 2, 3, 4)不编写数组创建的开销,但是MoreMath.Max(1, 2, 3, 4, 5, 6)当您不介意开销时,仍然可以编写出易于阅读且一致的代码。

我个人发现,这比LINQ方法的显式数组创建更具可读性。


2
如果您问这样的问题,max函数的性能很可能是无关紧要的,那么可读性将占上风。
巴斯

2
@安德鲁:我认为可以在一个地方阅读。如果我不止一次(但是每次仍然有3个参数),我可能宁愿编写一个自定义方法,也不使用LINQ方法。MoreMath.Max(x, y, z)比LINQ方法IMO更易读。
乔恩·斯基特

你为什么不习惯public static int Max(params int[] values) 呢?
Navid Rahmani

2
@Navid:因为调用as Max(1, 2, 3)将无缘无故创建一个数组。通过为相对少量的参数提供一些重载,可以提高效率,而不会影响调用方的可读性。
乔恩·斯基特

在优化代码之前,Math.Max似乎始终如一地表现得更好,随着我们从2-> 3-> 4的发展,引线的收缩也会缩小,即使添加MoreMath.Max(x,y)也会产生可衡量的开销。数学最大值〜(1,2)43ms,(2,1)〜38ms,内联〜(1,2)58ms,(2,1)〜53ms,委托〜(1,2)69ms,(2,1) 〜61ms。-> 3个值的数学运算:〜55ms,内联:〜62ms。-> 4个值:〜75ms vs〜80ms ...全部由1000万次迭代和5次测量完成...如果您启用优化功能,趋势转弯和Math赢得的数值越多,您赢的越多。但是...在性能很重要之前,您需要进行数十亿次比较。
詹斯


30

Linq具有Max函数。

如果您有一个IEnumerable<int>,可以直接调用它,但是如果您需要在单独的参数中使用它们,则可以创建如下函数:

using System.Linq;

...

static int Max(params int[] numbers)
{
    return numbers.Max();
}

然后您可以这样称呼它:max(1, 6, 2),它允许任意数量的参数。


2
是的,按照我编辑过的答案……除了我肯定要调用它Max而不是max,并使它成为静态的:)通过为更少的参数重载它,您也可以使它更有效。
乔恩·斯基特

1
@Jon Skeet:我们真的应该像这样为一个班轮编写函数吗?
naveen 2011年

5
@naveen:的确,如果它使代码更清晰,并且您正在多个地方使用它。为什么不?
乔恩·斯基特

@乔恩·斯基特:感谢您的澄清。这是我长期以来对设计的怀疑。去还是不去:)
naveen

12

作为通用

public static T Min<T>(params T[] values) {
    return values.Min();
}

public static T Max<T>(params T[] values) {
    return values.Max();
}

8

不在主题上,但这是中间值的公式..以防万一有人在寻找它

Math.Min(Math.Min(Math.Max(x,y), Math.Max(y,z)), Math.Max(x,z));

3

假设List<int> intList = new List<int>{1,2,3}您想获得最大值,可以这样做

int maxValue = intList.Max();

1

如果由于某种原因(例如,Space Engineers API),System.array没有为Max定义,也没有访问Enumerable的权限,则解决最大n个值的方法是:

public int Max(int[] values) {
    if(values.Length < 1) {
        return 0;
    }
    if(values.Length < 2) {
        return values[0];
    }
    if(values.Length < 3) {
       return Math.Max(values[0], values[1]); 
    }
    int runningMax = values[0];
    for(int i=1; i<values.Length - 1; i++) {
       runningMax = Math.Max(runningMax, values[i]);
    }
    return runningMax;
}

0

您可以尝试以下代码:

private float GetBrightestColor(float r, float g, float b) { 
    if (r > g && r > b) {
        return r;
    } else if (g > r && g > b) { 
        return g;
    } else if (b > r && b > g) { 
        return b;
    }
}

如果数字相同,则不会返回任何内容。
Zuabros

0

priceValues []中的最大元素值是maxPriceValues:

double[] priceValues = new double[3];
priceValues [0] = 1;
priceValues [1] = 2;
priceValues [2] = 3;
double maxPriceValues = priceValues.Max();

0

此函数采用整数数组。(我完全理解@Jon Skeet对发送数组的抱怨。)

这可能有点矫kill过正。

    public static int GetMax(int[] array) // must be a array of ints
    {
        int current_greatest_value = array[0]; // initializes it

        for (int i = 1; i <= array.Length; i++)
        {
            // compare current number against next number

            if (i+1 <= array.Length-1) // prevent "index outside bounds of array" error below with array[i+1]
            {
                // array[i+1] exists
                if (array[i] < array[i+1] || array[i] <= current_greatest_value)
                {
                    // current val is less than next, and less than the current greatest val, so go to next iteration
                    continue;
                }
            } else
            {
                // array[i+1] doesn't exist, we are at the last element
                if (array[i] > current_greatest_value)
                {
                    // current iteration val is greater than current_greatest_value
                    current_greatest_value = array[i];
                }
                break; // next for loop i index will be invalid
            }

            // if it gets here, current val is greater than next, so for now assign that value to greatest_value
            current_greatest_value = array[i];
        }

        return current_greatest_value;
    }

然后调用函数:

int highest_val = GetMax (new[] { 1,6,2,72727275,2323});

// highest_val = 72727275
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.