Why is this code not calculating the average correctly?

Asked

Viewed 635 times

3

I probably have to be really bad at math today to not be able to make a simple code that calculates the average of two values... I just don’t understand what I did wrong... BTW, I hope the average is 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
  • What is the result you are giving? You even tested by putting the valor1 and the valor2 between parentheses? Type, (valor1 + valor2)/2?

  • @Willian If for example, the first value is 10 and the second is 5 the result is 12.5. I think it should be 7.5 or I don’t know math???

  • 1

    Take a look at the comment above, you’re forgetting the parentheses that separate the sum from the division. If you do not put the sum in parentheses, the account will first do the division and then the sum

  • @I didn’t know this was possible in C#, I thought it only allowed "simple" calculations... I’ll try! If it works, thank you!

2 answers

6


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

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

resultado = (valor1 + valor2) / 2

  • Thank you so much for explaining that it was possible to perform calculations of this kind in C#, it seems I still have a lot to learn... :)

  • For nothing, good luck :D

4

The problem is on the line:

resultado = valor1 + valor2 / 2;

It turns out that the division and multiplication operation always has 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;

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

I hope I’ve helped.

  • Thanks for answering, but someone answered first... But thanks for the help anyway :D

  • You’re welcome, good luck on your journey.

Browser other questions tagged

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