Error when calculating average

Asked

Viewed 85 times

1

I would like to take the sum of all salaries and divide by the amount of employees, but this giving error, when I compile says that this with 0 in the variables Count of the list and total.

public class Informacao
{
    public float salBruto { get; set; }
    public int numFilhos { get; set; }
}
class Ex2
{
    List<Informacao> info = new List<Informacao>();
    public void CadNovaPesquisa()
    {
        Informacao infoo = new Informacao();

        Console.Clear();

        Console.WriteLine("Informe seu salário bruto:");
        infoo.salBruto = float.Parse(Console.ReadLine());
        Console.WriteLine("Informe a quantidade de filhos:");
        infoo.numFilhos = Convert.ToInt32(Console.ReadLine());
        info.Add(infoo);
    }
    public void CalculaMedia()
    {
        int i = info.Count;
        float total;
        total = info.Sum(x => x.salBruto);
        Console.WriteLine(i);
        //float media = total / i;
        Console.WriteLine($"TOTAL: {total}");
        Console.ReadLine();

    }
  • Did the answer solve your question? Do you think you can accept it? See [tour] if you don’t know how you do it. This would help a lot to indicate that the solution was useful for you. You can also vote on any question or answer you find useful on the entire site (when you have 15 points).

1 answer

1

I didn’t even try to see the error since there are other problems in the code, writing the correct way works, although I would change several other things:

using static System.Console;
using System.Collections.Generic;
using System.Linq;

public class Program {
    private static List<Informacao> informacoes = new List<Informacao>();
    public static void Main() {
        CadNovaPesquisa();
        CadNovaPesquisa();
        CalculaMedia();
    }
    public static void CadNovaPesquisa()   {
        var informacao = new Informacao();
        WriteLine("Informe seu salário bruto:");
        if (!decimal.TryParse(ReadLine(), out var salBruto)) return;
        informacao.SalBruto = salBruto;
        WriteLine("Informe a quantidade de filhos:");
        if (!int.TryParse(ReadLine(), out var numFilhos)) return;
        informacao.NumFilhos = numFilhos;
        informacoes.Add(informacao);
    }
    public static void CalculaMedia() {
        var total = informacoes.Sum(x => x.SalBruto);
        WriteLine($"TOTAL: {total} MEDIA: {total/informacoes.Count}");
    }
}

public class Informacao {
    public decimal SalBruto { get; set; }
    public int NumFilhos { get; set; }
}

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

Browser other questions tagged

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