/ / Pokaż 7 liczb całkowitych wraz z odległością każdej z nich od średniej - c #

Pokaż 7 liczb całkowitych wraz z odległością od średniej - c #

Nie mogę wymyślić, jak pokazać wartościi jak daleko każda wartość jest od średniej. Oto kod, który mam, ale wiem, że nie jest poprawny. Próbowałem wszystkiego, aby zbliżyć się do tego, czego chce.

To zadanie domowe do lekcji online, więc nie ma wielu opcji pomocy. Dzięki za wszelkie uwagi!

int[] temp = new int[7];
int x;
string daysString;
for (x = 0; x < temp.Length; ++x)
{
Write("Enter the high temperature for the day: ");
daysString = ReadLine();
temp[x] = Convert.ToInt32(daysString);
}
WriteLine("n-----------------------------------------");
WriteLine("The high temperature for each of the 7 days you entered: ");
for (x = 0; x < temp.Length; ++x)
Write("{0, 6}", temp[x]);

//Step 3. Compute Average
double average = temp.Average();
WriteLine("");
WriteLine("n-----------------------------------------");
WriteLine("Average = {0}", average);

//Step 4. Find out how many numbers in the array are greater than the average.
int count = 0;
foreach (int i in temp)
{
if (i > average) count++;
}
Write("n----------------------------------------------");
WriteLine("");
WriteLine("How many days away each high temperature is from the average");
WriteLine("{0, 6}", count);

Odpowiedzi:

0 dla odpowiedzi № 1

Twój ostatni krok 4 robi coś innego, a tak naprawdę chcesz:

jak daleko są wszystkie 7 temperatury od średniej?

int[] distancesFromAverage = temp
.Select(temperature => (int)Math.Abs(temperature - average))
.ToArray();

Teraz możesz podać temperaturę i odległość do średniej:

for(int i = 0; i < temp.Length; i++)
Console.WriteLine($"Temperature: {temp[i]} Distance from average: {distancesFromAverage[i]}");

0 dla odpowiedzi nr 2

Może nie rozumiem pytania

jak daleko jest każda wartość od średniej

ale skoro już obliczyłeś średnią

foreach (int val in temp)
{
WriteLine(val - average);
}

powiedziałbym różnicę między twoją wartością a średnią ...

Jeśli masz wartość bazową spoza listy, jak sugerowano w komentarzu, i chcesz wiedzieć, ile dni po tej wartości obecnie jesteś

for (int i=0; i<temp.Length; i++)
{
WriteLine ($"The value {temp[i]} is {i+1} days after the average");
}

Średnia jest wartością niekoniecznie zawartąna liście (średnia 3, 5 i 8 to 6, co nie jest częścią listy), więc nie możesz naprawdę powiedzieć, ile dni jest wartość po średniej. Czy szukasz mediany zamiast wartości średnia? Następnie możesz posortować listę, wziąć średnią wartość, a następnie poszukać odległości do tej konkretnej wartości.