2011-02-05 16 views
6

To działa idealnie ... ale kiedy używam foreach zamiast, to nie działa. Nie rozumiem, że for i foreach są takie same.Największa i najmniejsza liczba w tablicy

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(); 


     } 
    } 
} 
+1

Pokaż nam kod foreach, którego wypróbowałeś i nie zadziałał. prawdopodobnie robisz coś złego –

+0

To nie działa z powodu sposobu, w jaki piszesz swoje pytania. : P (Ok, zostało to zmienione, mój komentarz już nie ma sensu) –

+0

Jestem ciekawy dlaczego mówisz 'int largest = array [9];'. Dlaczego nie brać domyślnie pierwszego elementu? –

Odpowiedz

25

Dlaczego tego nie używasz?

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

Pachnie jak zadanie domowe. Jego nauczyciel prawdopodobnie jeszcze tam nie poszedł. –

+0

Jeśli jest to praca domowa, prawdopodobnie będzie próbował zaimplementować metodę samodzielnie, zamiast używać wbudowanej (i być może znaleźć niezmienniki pętli). –

+0

+1, jeśli powiesz mi, gdzie mogę znaleźć Max(): p, nie wydaje się być w System.Array, używam długiego [] –

2

Użytkownik (normalnie) nie może modyfikować kolekcji, którą wykonuje iteracja podczas korzystania z foreach.

Chociaż dla i foreach wydaje się być podobny z punktu widzenia programisty, różnią się one znacznie od perspektywy wdrożenia. Aby uzyskać dostęp do poszczególnych obiektów,

Foreach uzyskuje dostęp do poszczególnych obiektów, podczas gdy for nie wie (lub nie obchodzi) o podstawowej sekwencji obiektów.

8

Jeśli trzeba użyć foreach (z jakiegoś powodu) i nie chce korzystać z funkcji BULT-in, oto fragment kodu:

int minint = array[0]; 
int maxint = array[0]; 
foreach (int value in array) { 
    if (value < minint) minint = value; 
    if (value > maxint) maxint = value; 
} 
1
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(); 
     } 
    } 
} 
+0

Dlaczego ten kod nie działa dla mnie? – tandem

+0

wszystkie linie kodu muszą być wcięte (przynajmniej) 4 spacje, aby formater mógł działać. Również muszą być oddzielone od otaczającego tekstu (jeśli jest) pustą linią. –

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

W ten sposób można mają najmniejszą i największą liczbę w pojedynczej pętli.

+0

Nie ma wymogu dla zmiennych tymczasowych, a następnie ponownego przypisania do tablicy. –

0
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); 
    } 
+1

Podczas gdy ten kod może odpowiedzieć na pytanie, podanie dodatkowego kontekstu dotyczącego tego, dlaczego i/lub jak ten kod odpowiada na pytanie, poprawia jego długoterminową wartość. – Bono

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

Oto kompletny program dać Poniżej `

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(); 

     } 

    } 












     } 
0
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();   
     } 
    } 
} 
0

Jest to długi czas. Może tak:

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; 
    } 
Powiązane problemy