Algorithm VisualG: disregard number 0

1

I'm solving the following exercise:

  

Write an algorithm that calculates the mean of the numbers entered by the user, if they are even. Finish reading if user types zero (0)

However, when I type 0 to finish, it counts 0 as even number, and is dividing by an extra number.

algoritmo "semnome"

var
n,np,m,nnp:real
inicio
repita
escreval ("entre com um numero")
leia (n)
se n%2=0 entao
np<-np+1
nnp<-nnp+n
fimse
ate n=0
m<- nnp/np
escreval ("a media dos numeros é",m)
fimalgoritmo
    
asked by anonymous 10.07.2018 / 18:06

1 answer

4

Only add a criterion in the condition:

  

If the number is not zero (it is non-zero) and the remainder of the division by 2 equals zero.

Just to leave some tips: watch the formatting of the code, indentation. This is important. Give really useful names to variables, no one likes having to read the whole code to understand what the np variable means in scope, and believe me, you also will not like doing this when reading your old code. >

algoritmo "semnome"

var
numero, qtd, media, soma: real

inicio

repita
   escreval ("entre com um numero")
   leia (numero)
   se (numero diferente de 0) E (numero % 2 = 0) entao
      qtd <- qtd + 1
      soma <- soma + numero
   fimse
ate numero = 0

media <- soma/qtd

escreval ("a media dos numeros é", media)
fimalgoritmo
    
10.07.2018 / 18:19