有没有办法在C#中找出3个数字的最大值?

Is there a method to find the max of 3 numbers in C#?(有没有办法在C#中找出3个数字的最大值?)

本文介绍了有没有办法在C#中找出3个数字的最大值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

该方法的工作方式应与Math.Max()类似,但接受3个或更多int参数。

推荐答案

嗯,只能调用两次:

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

如果您发现自己经常这样做,您可以随时编写自己的帮助器方法……我会很高兴在我的代码库中看到这一点一次,但不是经常看到。

(请注意,这可能比Andrew的基于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方法的显式数组创建更具可读性。

这篇关于有没有办法在C#中找出3个数字的最大值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:有没有办法在C#中找出3个数字的最大值?

基础教程推荐