Variable never reaches zero using Randi

Asked

Viewed 406 times

0

Could I show you Life: 0 in the Visualg console output?

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

If anyone can help me, I’d appreciate it.

The version of my Visualg is the 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

inserir a descrição da imagem aqui

inserir a descrição da imagem aqui

  • Try with life <= 0. Why damage receives randi(life)?

  • Ate(life <= 0) looped in as well. damage receives randi(life) in order to generate a random number from the 100 why life <- 100. The randi is a randomization function.

  • Is there an example of the output when it loops? By the way, randi(life) can return life or is 0 to life-1?

  • Replaces damage <- randi(life) for damage <- randi(80). Now it’s stopped looping even with Ate(life <= 0). Looks like it’s working now. Click here to see the image

  • Yeah, so you can use life = 0 and put randi(life+1)

  • Only as an aside, if you are in a language where the reserved words are in Portuguese, why not use variable names also in Portuguese ?

  • randi(life+1) also worked, I think it solves better than my gambiarra to put randi(80). Thank you.

  • That’s why life was coming to 0 and the randi was trying to randomize the 0, so I was looping in.

  • Truth @Isac, I could have followed the Portuguese, but it was just for testing, thanks for helping me.

Show 4 more comments

1 answer

0


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

To solve, just do randi(life+1), to draw a set value [0, life+1[, or [0, life], and thus life will at some point come to zero, being able to maintain the life = 0:

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
  • It worked perfectly! Thank you.

Browser other questions tagged

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