Why is not this code calculating the mean correctly?

3

I probably should be really bad at math today so I can not do a simple code that calculates the average of two values ... I just do not understand what I did wrong ... BTW, I expect the average to be calculated like this ... (sum of several values / amount of values, in this case valor1 + valor2 /2 )

double valor1 = 0; // Valor a calcular
double valor2 = 0; // Segundo valor a calcular
double resultado = 0; // Variável para mostrar o resultado

Console.Write("Escreva o primeiro valor da para calcular a média: "); // Perguntar o primeiro valor
valor1 = double.Parse(Console.ReadLine()); // Leitura + conversão da string para double
//
Console.Write("Escreva o segundo valor: "); // Perguntar o segundo valor
valor2 = double.Parse(Console.ReadLine()); // Leitura + conversão da string para double

resultado = valor1 + valor2 / 2; // Cálculo da média -> valor1 + valor2 / 2

Console.WriteLine("O resultado é: " + resultado); // Mostrar o resultado
Console.Read(); // Pausar a aplicação e permitir o utilizador ler o resultado
    
asked by anonymous 28.10.2016 / 20:31

2 answers

7

As shown in the comments, the error is in resultado = valor1 + valor2 /2 .

By math, if you want the sum to be done before splitting, you have to put the sum in parentheses and then divide. In case it would be:

resultado = (valor1 + valor2) / 2

    
28.10.2016 / 20:43
5

The problem is on the line:

resultado = valor1 + valor2 / 2;

It turns out that the division and multiplication operation always takes priority over addition and subtraction, if you want to specify that an addition is more important in your context you should do the following:

resultado = (valor1 + valor2) / 2;

In this way the addition will be executed first and the result will be divided by the number 2.

I hope I have helped.

    
28.10.2016 / 20:45