Error when doing sum inside foreach

Asked

Viewed 75 times

0

I have this method CadastroDespesas, only that he is making the wrong sum in foreach going through my list.

I don’t know what it is, if anyone can help me...

To totdesp is a global variable declared in my class).

class Ex4
{
    List<String> descricaodespesas = new List<string>();
    List<float> valordespesas = new List<float>();
    List<String> descricaoreceitas = new List<string>();
    List<float> valorreceitas = new List<float>();
    float totdesp, totreceit;
    float mediareceit, mediadesp;

    public void CadastroDespesas()
    {
        string descricao;
        float valor,somadesp = 0;
        Console.Write("Informe o valor: ");
        valor = Convert.ToSingle(Console.ReadLine());
        valordespesas.Add(valor);
        Console.WriteLine("Informe uma descrição:");
        descricao = (Console.ReadLine());
        descricaodespesas.Add(descricao);
        foreach (float som in valordespesas)
        {
            somadesp += valor;
        }
        totdesp = somadesp;
    }
}

2 answers

3

The mistake is that you are going through the valordespesas but always adds up the same value; you need to add som, nay valor:

foreach (float som in valordespesas)
{
    somadesp += som;
}
  • 1

    Vlw Amigo, you solved the problem here. :)

  • @Guilhermeschubertmedeiros, if the answer is correct, mark as accepted ;)

1

Another option is not to use the foreach() and yes the method Sum()

totdesp = valordespesas.Sum();

Browser other questions tagged

You are not signed in. Login or sign up in order to post.