Error at the time of summing inside the foreach

0

I have this method CadastroDespesas , only it is doing the wrong sum in the foreach that runs through my list.

I do not know what it is, if someone can help me ...

A 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;
    }
}
    
asked by anonymous 14.03.2018 / 20:04

2 answers

3

The error is that you are correctly traversing valordespesas but always adding the same value; you need to add som , not valor :

foreach (float som in valordespesas)
{
    somadesp += som;
}
    
14.03.2018 / 20:07
1

Another option is to neither use foreach() , but method Sum()

totdesp = valordespesas.Sum();
    
14.03.2018 / 21:48