2013-07-10 25 views
5

Jak utworzyć metodę, która wyklucza najniższą temperaturę i obliczyć średnią temp.? Chcę tylko podpowiedzi, a nie kompletne rozwiązanie, ponieważ sam chcę rozwiązać moje problemy programistyczne. Miałem tylko około 10 lekcji .. aby komentować komentarze ludzi, których mój wykładowca nie wykłada i przeczytałem, że moja książka przegląda je wielokrotnie.Jak wykluczyć wartość tablicy?

Zrobiłem program, aby pobrać numer od użytkownika. Ta liczba jest dodawana do tablicy. Ta tablica jest używana do utworzenia instancji klasy Temp w celu wydrukowania najniższych i najwyższych tempa.

class Program 
{ 
    static void Main(string[] args) 
    { 
     Console.Write("Enter a Temperature in Degrees:"); 
     string n = Console.ReadLine(); 
     int number = Convert.ToInt32(n); 
     Temp t = new Temp(100, 52, 98, 30, 11, 54, number); 
     Console.WriteLine("Lowest Temperature:{0}", t.lowest()); 
     Console.WriteLine("Highest Temperature: {0}", t.highest()); 
     Console.WriteLine("Average Temperature: {0}", t.Average()); 
    } 

    public class Temp 
    { 
     private int[] temp = new int[7]; // array 
     public Temp(int d1, int d2, int d3, int d4, int d5, int d6, int d7) // constructor with 7 parameters 
     { 
      temp[0] = d1; // assigning constructor parameters to array 
      temp[1] = d2; 
      temp[2] = d3; 
      temp[3] = d4; 
      temp[4] = d5; 
      temp[5] = d6; 
      temp[6] = d7; 
     } 

     public int lowest() // returning the lowest value of the set of numbers 
     { 
      int smallest = 150; 
      for (int c = 0; c < 7; c++) 
      { 
       if (temp[c] < smallest) 
       { 
        smallest = temp[c]; 
       } 

      } 
      return smallest; 
     } 

     public int highest() 
     { 
      int highest = -1; 
      for (int c = 0; c < 7; c++) 
      { 
       if (temp[c] > highest) 
       { 
        highest = temp[c]; 
       } 
      } 

      return highest; 
     } 

     public double Average() 
     { 
      double average = 0; 
      for (int c = 0; c < 7; c++) 
      { 

      } 
      return average; 
     } 
    } 
} 

Odpowiedz

8

Jest to bardzo proste do zrobienia z jednej pętli:

public double Average() 
{ 
    // Initialize smallest with the first value. 
    // The loop will find the *real* smallest value. 
    int smallest = temp[0]; 

    // To calculate the average, we need to find the sum of all our temperatures, 
    // except the smallest. 
    int sum = temp[0]; 

    // The loop does two things: 
    // 1. Adds all of the values. 
    // 2. Determines the smallest value. 
    for (int c = 1; c < temp.Length; ++c) 
    { 
     if (temp[c] < smallest) 
     { 
      smallest = temp[c];  
     } 
     sum += temp[c]; 
    } 
    // The computed sum includes all of the values. 
    // Subtract the smallest. 
    sum -= smallest; 

    double avg = 0; 
    // and divide by (Length - 1) 
    // The check here makes sure that we don't divide by 0! 
    if (temp.Length > 1) 
    { 
     avg = (double)sum/(temp.Length-1); 
    } 
    return avg; 
} 
+1

+1: Wolę tę odpowiedź od tej, którą zasugerowałem. – Douglas

1

Trzeba dodać obsługę błędów, ale może to pomóc daje początek

var ints = new List<int>(); 
var newInts = ints.OrderBy(x => x).ToList(); 
newInts.RemoveAt(0); 
var avg = newInts.Average(); 
0

Można to zrobić łatwo z kilku funkcji LINQ. Istnieje wiele innych sposobów, aby to zrobić, ale wszystkie będą podobne. Jeśli jest więcej niż jedna wartość min, twoja średnia nie będzie zawierała żadnego z nich.

int min = myArray.Min(); // get the min element 
var withoutMin = myArray.Where(x => x != min); // get a new list without the min element 
double mean = withoutMin.Average(); // take the sum and divide it by the count 
+0

to będzie nieważne, jeśli istnieje wiele elementów, które są równe Min. – Sayse

+0

@ Sayse niekoniecznie. To zależy od charakterystyki listy i tego, jak definiujesz Min. Myślę, że wynika to z konwencji rachunku matematycznego/lambda. Wprowadziłem jednak edycję, żeby to wskazać. – evanmcdonnal

+0

Zauważyłem :) w uczciwości, możesz użyć 'Average()' zamiast ostatniej linii – Sayse

0
public double Average() 
    { 
     var tempsToUse = temp.OrderByDescending(t => t).Take(temp.Length - 1); 

     return tempsToUse.Average(); 
    } 

edytowane zawierać pełną sygnaturę funkcji.

2

Tutaj jest trochę inna wersja niż Douglas pisał (oczywiście jego wersja jest zupełnie w porządku i dobrze opisane, po prostu umieścić go na swój przejrzeć). Nie używa najniższego() wywołania metody.

public double Average() 
{ 
    double sum = temp[0]; // sum of temperatures, starting from value of first one in array 
    double lowest = temp[0]; // buffer for lowest temperature value 
    for (int c = 1; c < 7; c++) // start loop from second position in array 
    { 
     if (temp[c] < lowest) // checking if next value in array is smaller than the lowest one so far... 
     { 
      lowest = temp[c]; // ...if so, value of variable lowest is changing 
     } 
     sum = sum + temp[c]; // adding temparatures value to variable sum, one by one 
    } 
    sum = sum - lowest; // at the end we substract lowest value from sum of all temperatures 
    double average = sum/6; // average value calculation 
    return average; 
} 

EDYCJA: Jim Mischel był pierwszy ;-). Jego wersja jest również bardziej elastyczna dzięki użyciu wartości temp.Length, a nie statycznej (w tym przypadku 7).

+0

dlaczego użyłeś temp [0] .. Zakładam, że przyjmujesz, że temp [0] jest zawsze najniższym zestawem temperatur. czy tylko po prostu inicjalizujesz wartość sumy i najniższej? –

+0

@ZachB: Po prostu inicjowanie. Jest to nieco bardziej skuteczny sposób robienia tego, ponieważ zmniejsza liczbę iteracji o jeden. – Douglas

Powiązane problemy