What’s wrong with my code?

Asked

Viewed 143 times

0

algoritmo "Calculadora"

Var
num1, num2, r: real
operacao: caractere

inicio

EscrevaL("Digite: ")
leia(num1, operacao, num2)

caso operacao "+"
r <- num1 + num2

caso operacao "-"
r <- num1 - num2

caso operacao "*"
r <- num1 * num2

caso operacao "/"
r <- num1 / num2

EscrevaL("Resultado:", r)

fimalgoritmo

Basically, it doesn’t have the right values, and how could I type in the direct operation, like, 2+2? I tried to do it there, so much so that I read three variables, and it didn’t work. I had to type like this: 2 + 2 So he would recognize, but, as the way I reported above, I could not do. I entered the value 3 + 3, resulted in 9, what am I missing? How can I improve code/fix?

1 answer

0


There’s an error in the structure of your code.

To implement a CASE structure in Visualg you must declare it as follows:

choosing case ... child

Your correct code would look like this:

algoritmo "calculadora"
var
num1, num2, r: real
operacao: caractere

inicio
// Seção de Comandos
EscrevaL("Digite: ")
leia(num1, operacao, num2)

escolha operacao

caso "+"
r <- num1 + num2

caso "-"
r <- num1 - num2

caso "*"
r <- num1 * num2

caso "/"
r <- num1 / num2

fimescolha

EscrevaL("Resultado:", r)

fimalgoritmo

Look at the sections escolha operacao and fimescolha encapsulating the CASE structure.

  • Thank you, but you can answer another question?

  • It worked. But, how can I do to for example type the expression direct? For example: 2+2 instead of having to do it that way 2, line jumper, +, line jumper, 2? Example: http://prntscr.com/do9npv

  • To type everything in a row you will need to go further: you will need to implement a lexical parser, a parser. Then the subject is more in the area of compilers and formal languages. For simple expressions it is not necessary, but for expressions like (1 + (3 * 5) - 4) / 2, it is impossible to do otherwise. I do not know if it is possible to do this in Visualg. In time, if my previous answer answers your question, please mark it as such.

Browser other questions tagged

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