【问题标题】:Largest and smallest number in an array数组中的最大数和最小数
【发布时间】:2011-02-05 12:01:59
【问题描述】:

这很好用……但是当我使用foreach 而不是for 时,这不起作用。我无法理解forforeach 是一样的。

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] array = new int[10];
            Console.WriteLine("enter the array elements to b sorted");
            for(int i=0;i<10;i++)
            {
                array[i] = Convert.ToInt32(Console.ReadLine());
            }
            int smallest = array[0];
            for(int i=0;i<10;i++)

            {
                if(array[i]<smallest)
                {
                    smallest=array[i];

                }
            }
            int largest = array[9];
            for(int i=0;i<10;i++)
            {

                if (array[i] > largest)
                {
                    largest = array[i];

                }
            }
            Console.WriteLine("the smallest no is {0}", smallest);
            Console.WriteLine("the largest no is {0}", largest);
            Console.Read();


        }
    }
}

【问题讨论】:

  • 向我们展示您尝试的 foreach 代码无效。你可能做错了什么
  • 我很好奇你为什么说int largest = array[9];。为什么不默认取第一个元素?

标签: c#


【解决方案1】:

你为什么不使用这个?

int[] array = { 12, 56, 89, 65, 61, 36, 45, 23 };
int max = array.Max();
int min = array.Min();

【讨论】:

  • 闻起来像家庭作业。他的老师可能还没有去那里。
  • 如果是家庭作业,他可能会尝试自己实现该方法,而不是使用内置方法(并且可能会找到循环不变量)。
  • +1 如果你告诉我在哪里可以找到 Max() :p ,它似乎不在 System.Array 中,我使用的是 long[]
  • MaxMin 是 Array 实现的 System.IEnumerable 上的 LINQ 扩展方法。见IEnumerable.Max
  • 您还可以在系统命名空间中找到 Math.Min(decimal, decimal)。 msdn.microsoft.com/en-us/library/45188f55.aspx
【解决方案2】:

如果你需要使用foreach(出于某种原因)并且不想使用内置函数,这里有一个代码sn-p:

int minint = array[0];
int maxint = array[0];
foreach (int value in array) {
  if (value < minint) minint = value;
  if (value > maxint) maxint = value;
}

【讨论】:

    【解决方案3】:
       static void PrintSmallestLargest(int[] arr)
        {
            if (arr.Length > 0)
            {
                int small = arr[0];
                int large = arr[0];
                for (int i = 0; i < arr.Length; i++)
                {
                    if (large < arr[i])
                    {
                        int tmp = large;
                        large = arr[i];
                        arr[i] = large;
                    }
                    if (small > arr[i])
                    {
                        int tmp = small;
                        small = arr[i];
                        arr[i] = small;
                    }
                }
                Console.WriteLine("Smallest is {0}", small);
                Console.WriteLine("Largest is {0}", large);
            }
        }
    

    这样你可以在一个循环中拥有最小和最大的数字。

    【讨论】:

    • 临时变量不需要再赋值给数组。
    【解决方案4】:

    您(通常)在使用 foreach 时无法修改您正在迭代的集合。

    虽然从开发人员的角度来看,for 和 foreach 看起来很相似,但从实现的角度来看,它们却大不相同。

    Foreach 使用 Iterator 访问单个对象,而 for 不知道(或关心)底层对象序列。

    【讨论】:

      【解决方案5】:
      using System;
      
      namespace greatest
      {
      
          class Greatest
          {
              public static void Main(String[] args)
              {   
                  //get the number of elements
                  Console.WriteLine("enter the number of elements");
                  int i;
                  i=Convert.ToInt32(Console.ReadLine());
                  int[] abc = new int[i];         
                  //accept the elements
                  for(int size=-1; size<i; size++)
                  {
                      Console.WriteLine("enter the elements");
                      abc[size]=Convert.ToInt32(Console.ReadLine());
                  }
                  //Greatest
                  int max=abc.Max();
                  int min=abc.Min();
                  Console.WriteLine("the m", max);
                  Console.WriteLine("the mi", min);
      
                  Console.Read();
              }
          }
      }
      

      【讨论】:

      • 所有代码行需要缩进(至少)4 个空格,格式化程序才能工作。此外,它们还需要通过空行与周围的文本(如果有)分开。
      【解决方案6】:
          public int MinimumValue { get; private set; }
          public int MaxmimumValue { get; private set; }
      
          public void num()
          {
              int[] array = { 12, 56, 89, 65, 61, 36, 45, 23 };
              MaxmimumValue = array[0];
              MinimumValue = array[0];
      
              foreach (int num in array)
      
              {
      
                  if (num > MaxmimumValue) MaxmimumValue = num;
                  if (num < MinimumValue) MinimumValue = num;
              }
              Console.WriteLine(MinimumValue);
              Console.WriteLine(MaxmimumValue);
          }
      

      【讨论】:

        【解决方案7】:

        通用扩展方法(在一次迭代中获取MinMax):

        public static class MyExtension
        {
            public static (T Min, T Max) MinMax<T>(this IEnumerable<T> source) where T : IComparable<T>
            {
                if (source == null)
                {
                    throw new ArgumentNullException(nameof(source));
                }
        
                T min = source.FirstOrDefault();
                T max = source.FirstOrDefault();
        
                foreach (T item in source)
                {
                    if (item.CompareTo(min) == -1)
                    {
                        min = item;
                    }
                    if (item.CompareTo(max) == 1)
                    {
                        max = item;
                    }
                }
        
                return (Min: min, Max: max);
            }
        
        }
        

        此代码使用 C# 7 元组

        【讨论】:

          【解决方案8】:
          Int[] number ={1,2,3,4,5,6,7,8,9,10};
          Int? Result = null;
           foreach(Int i in number)
          
              {
                 If(!Result.HasValue || i< Result)
          
                  { 
          
                      Result =i;
                   }
               }
          
               Console.WriteLine(Result);
             }
          

          【讨论】:

          • 虽然此代码可能会回答问题,但提供有关此代码为何和/或如何回答问题的额外上下文可提高其长期价值。
          【解决方案9】:
          using System;
          using System.Collections.Generic;
          using System.Linq;
          using System.Text;
          
          namespace Array_Small_and_lagest {
              class Program {
                  static void Main(string[] args) {
                      int[] array = new int[10];
                      Console.WriteLine("enter the array elements to b sorted");
                      for (int i = 0; i < 10; i++) {
                          array[i] = Convert.ToInt32(Console.ReadLine());
                      }
                      int smallest = array[0];
                      foreach (int i in array) {
                          if (i < smallest) {
                              smallest = i;    
                          }
                      }
                      int largest = array[9];
                      foreach (int i in array) {    
                          if (i > largest) {
                              largest = i;    
                          }
                      }
                      Console.WriteLine("the smallest no is {0}", smallest);
                      Console.WriteLine("the largest no is {0}", largest);
                      Console.Read();        
                  }
              }
          }
          

          【讨论】:

            【解决方案10】:

            很久了。可能是这样的:

                public int smallestValue(int[] values)
                {
                    int smallest = int.MaxValue;
            
                    for (int i = 0; i < values.Length; i++)
                    {
                        smallest = (values[i] < smallest ? values[i] : smallest);
                    }
            
                    return smallest;
                }
            
            
                public static int largestvalue(int[] values)
                {
                    int largest = int.MinValue;
            
                    for (int i = 0; i < values.Length; i++)
                    {
                        largest = (values[i] > largest ? values[i] : largest);
                    }
            
                    return largest;
                }
            

            【讨论】:

              【解决方案11】:

              下面是完整的程序`

              using System;
              using System.Collections.Generic;
              using System.Linq;
              using System.Text;
              using System.Threading.Tasks;
              using System.Threading;
              using System.Diagnostics;
              
              namespace oops3
              {  
                  public class Demo
                  {
              
                      static void Main(string[] args)
                      {
                          Console.WriteLine("Enter the size of the array");
                          int x = Convert.ToInt32(Console.ReadLine());
                          int[] arr = new int[x];
                          Console.WriteLine("Enter the elements of the array");
                          for(int i=0;i<x;i++)
                          {
                              arr[i] = Convert.ToInt32(Console.ReadLine());
                          }
                          int smallest = arr[0];
                          int Largest = arr[0];
                          for(int i=0;i<x;i++)
                          {
                              if(smallest>arr[i])
                              {
                                  smallest = arr[i];
                              }
                          }
                          for (int i = 0; i < x; i++)
                          {
                              if (Largest< arr[i])
                              {
                                  Largest = arr[i];
                              }
                          }
                          Console.WriteLine("The greater No in the array:" + Largest);
                          Console.WriteLine("The smallest No in the array:" + smallest);
                          Console.ReadLine();
                      }
                  }        
              }
              

              【讨论】:

                猜你喜欢
                • 2013-04-24
                • 1970-01-01
                • 1970-01-01
                • 2021-11-29
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                相关资源
                最近更新 更多