1
help for Recursive Function that prints the average of the elements of an integer list and the number of elements larger than the average. in c#
good, what I have so far, is giving System.Stackoverflowexception error.
public static Double MediaLista(Double[] v)
{
int i = 0;
Double soma = 0;
if (i < v.Length)
{
for (int j = 0; j < v.Length; j++)
{
soma += v[j];
}
i++;
return soma / MediaLista(v);
}
else return 0;
}
static void Main(string[] args)
{
Double[] v = {1,2,3,3,5};
Double resul = MediaLista(v);
}
Edit : I increased the functionality of taking the numbers larger than the average in the Medialist method itself. In all my method was like this.
public static double MediaLista(int[] v, int ultimo)
{
if (ultimo == 0)
{
return v[0];
}
else
{
int qtdNumero = ultimo + 1;
double soma = v[ultimo] + (qtdNumero - 1) * MediaLista(v, ultimo - 1);
if (qtdNumero == v.Length) {
for (int i = 0; i < v.Length; i++)
{
if (v[i] > (soma / qtdNumero))
{
Console.WriteLine($"o numero {v[i]} é maior que a média");
}
}
}
return soma / qtdNumero;
}
}
Please add the code to your question.
– SylvioT
Welcome to Stackoverflow. Take a look at tour from the site for some tips on how to formulate the question and make some changes to it, because the way it looks is that you want someone to do it for you instead of helping you.
– Ronaldo Araújo Alves
opa, added
– Arlindo Cruz Machado
There’s probably a key lock left.
– Gustavo Luciano
is on a loop, just as @Ronaldoaraújoalves said...
– LeoHenrique
Return sum / Medialist(v); sum Return = 0 / 0 = overflow. Take your calculator there and divide 0 / 0. You will have undefined value or in c# stackoverflow pq no if tá lá que se i < v vai pro loop, se o i = 0 then you will never finish this.
– user148827
Divide some number by 0 gives Dividebyzeroexception
– Ronaldo Araújo Alves
Meeeeu God, I can’t believe I gaffed that kkkk, right. But I don’t understand why it’s recursive. The idea is to calculate the average of this list of elements and show those that are above this average point. Why call again? The next call is to calculate which are above the average and stop recursion there?
– user148827
It’s an exercise in logic as I understand it. The idea is not the result, it’s training
– Ronaldo Araújo Alves
It is, as I tbm am beginner in c# (came from Vb.net) to breaking the head here pq had never used recursiveness, but I managed to do even the media, missing to get which elements are bigger q the media.
– user148827
Cool @Vanderleijunior , I took your logic to get the numbers bigger than the average and I incremented the average method. This should not change in function recursiveness.
– Arlindo Cruz Machado