Variable never reaches zero using randi

0

Would you like to show Life: 0 in the VisuAlg console result?

I tried to put Ate (life = 0) but it gives infinite loop.

If someone can help me, I appreciate it.

The version of my VisuAlg is 2.0

algoritmo "RPG"
var
   damage, life: Inteiro
inicio
   life <- 100
   EscrevaL("Vida: ", life)
   Repita
       EscrevaL(" >>> Dano causado: ", damage)
       EscrevaL("Vida: ", life)
       damage <- randi(life)
       life <- life - damage
   Ate(life = 1)
   Se (life = 1) entao
       EscrevaL("Inimigo abatido!")
   FimSe
fimalgoritmo

    
asked by anonymous 06.06.2018 / 09:51

1 answer

0

The randi(x) function returns a random number in the [0, x[ set, that is, a number between 0 and x-1 . This way, there will come a time that will only be 1 life ( life = 1 ) and doing randi(life) will always return 0. If it always returns zero, life will never be less than 1, entering a loop infinite - and this explains why when you made the condition life = 1 the program ended.

To solve, just make randi(life+1) , so that a value of the set [0, life+1[ , or [0, life] is drawn, and thus, life will eventually reach zero, being able to keep the life = 0 condition:

algoritmo "RPG"
var
   dano, vida: Inteiro
inicio
   life <- 100
   EscrevaL("Vida: ", vida)
   Repita
       dano <- randi(vida+1)
       vida <- vida - dano
       EscrevaL(" >>> Dano causado: ", dano)
       EscrevaL("Vida: ", vida)
   Ate(vida = 0)
   EscrevaL("Inimigo abatido!")
fimalgoritmo
    
06.06.2018 / 13:17