【问题标题】:Is there a method to find the max of 3 numbers in C#?有没有办法在 C# 中找到最多 3 个数字?
【发布时间】:2011-10-11 15:58:02
【问题描述】:

该方法应该像 Math.Max() 一样工作,但需要 3 个或更多 int 参数。

【问题讨论】:

  • 这些数字在哪里?它们是如何存储的?

标签: c# max


【解决方案1】:

如果不想重复调用Max函数,可以这样

new List<int>() { A, B, C, D, X, Y, Z }.Max()

【讨论】:

    【解决方案2】:

    如果出于某种原因(例如 Space Engineers API),System.array 没有 Max 的定义,您也无权访问 Enumerable,Max of 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;
    }
    

    【讨论】:

      【解决方案3】:

      这个函数接受一个整数数组。 (我完全理解@Jon Skeet 关于发送数组的抱怨。)

      这可能有点矫枉过正。

          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
      

      【讨论】:

        【解决方案4】:

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

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

        【讨论】:

          【解决方案5】:

          你可以试试这个代码:

          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;
              }
          }
          

          【讨论】:

          • 如果数字相同,则不会返回任何内容。
          【解决方案6】:

          通用

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

          【讨论】:

            【解决方案7】:

            题外话,但这里是中间值的公式..以防万一有人在寻找它

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

            【讨论】:

              【解决方案8】:

              Linq 有一个Max 函数。

              如果您有IEnumerable&lt;int&gt;,您可以直接调用它,但如果您需要在单独的参数中使用它们,您可以创建如下函数:

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

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

              【讨论】:

              • 是的,根据我编辑的答案...除了我肯定想称它为 Max 而不是 max,并使其成为静态 :) 通过重载它以减少参数,你也可以提高效率。
              • @Jon Skeet:我们真的应该为这样的一个班轮编写函数吗?
              • @naveen:当然,如果它使代码更清晰,并且您在多个地方使用它。为什么不呢?
              • @Jon Skeet:感谢您的澄清。这是我长期以来的一个设计疑问。去还是不去:)
              【解决方案9】:

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

              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 方法的 显式 数组创建更具可读性。

              【讨论】:

              • 如果你问这样的问题,max函数的性能很可能是无关紧要的,可读性会占上风。
              • @Andrew:我认为可以在 one 的地方阅读。如果我不止一次拥有它(但每次仍然有 3 个参数),我可能宁愿编写自定义方法而不是使用 LINQ 方法。 MoreMath.Max(x, y, z) 比 IMO 的 LINQ 方法更具可读性。
              • 你为什么不直接使用public static int Max(params int[] values) ?
              • @Navid:因为将其称为Max(1, 2, 3) 将无缘无故地创建一个数组。通过为相对少量的参数提供一些重载,您可以在不影响调用者的可读性的情况下提高效率。
              • Math.Max 似乎一直表现得更好,直到您优化代码,它的领先优势随着我们从 2 -> 3 -> 4 开始缩小,即使添加 MoreMath.Max(x, y) 也会产生可测量的高架。 Math.Max ~ (1,2) 43ms, (2,1) ~38ms, 内联 ~ (1,2) 58ms, (2,1) ~53ms, Delegated~ (1,2) 69ms, (2,1)约 61 毫秒。 -> 3 个值的数学运算:~55ms,内联:~62ms。 -> 4 个值:~75ms vs ~80ms...全部由 1000 万次迭代和 5 次测量完成...如果您打开优化,趋势会发生变化,并且 Math 赢得的值越多,您添加的值越多。但是...在性能变得重要之前,您需要进行数十亿次比较。
              【解决方案10】:

              假设你有一个List&lt;int&gt; intList = new List&lt;int&gt;{1,2,3},如果你想获得一个最大值你可以这样做

              int maxValue = intList.Max();
              

              【讨论】:

                【解决方案11】:

                你可以使用Enumerable.Max:

                new [] { 1, 2, 3 }.Max();
                

                【讨论】:

                • 我不知道您可以使用 [] 创建一个 Enumerable。漂亮。
                • @MateenUlhaq 它是new int[] { 1,2,3 } 的简写。所以它是一个int类型的数组,由它的内容隐式决定。
                猜你喜欢
                • 2013-06-18
                • 1970-01-01
                • 2020-07-26
                • 1970-01-01
                • 1970-01-01
                • 2012-06-05
                • 1970-01-01
                • 2013-02-17
                • 2022-07-08
                相关资源
                最近更新 更多