Problem with the calculator in Go [BEGINNER]

Asked

Viewed 85 times

-2

Guys, I’m a beginner in programming and I’m trying to practice doing a calculator in Go. Can anyone explain to me why when I try to calculate, the results are always returning me the 0? Am I forgetting to return something? I can’t understand what I’m missing.

    func menu() {
    
        fmt.Println("Qual operação deseja fazer?")
    
        fmt.Println("1) Soma? ")
        fmt.Println("2) Subtração? ")

    
    }
    
    func main() {
        var num1, num2, resposta int
        var soma int = num1 + num2
        var subtracao int = num1 - num2
    
        fmt.Println("Bem-vindo(a) a calculadora!")
    
        fmt.Println("Digite o valor do primeiro número: ")
        fmt.Scanln(&num2)
    
        fmt.Println("Digite o valor do segundo número: ")
        fmt.Scanln(&num2)
    
        menu()
        fmt.Scanln(&resposta)
        switch resposta {
        case 1:
            fmt.Println(soma)
        case 2:
            fmt.Println(subtracao)
        default:
            fmt.Println("Número inválido!")
        }
    
    }

1 answer

0


You’re performing the operations before you even get the entries, so go uses the initial values of the variables to get the result.

Another error in your code is that you are reading the entries in the variable num2 what will end up writing the same.

func main() {
        var num1, num2, resposta int
        //soma e subtracao tem que ir para depois de obter as entradas
        var soma int = num1 + num2
        var subtracao int = num1 - num2
    
        fmt.Println("Bem-vindo(a) a calculadora!")
    
        fmt.Println("Digite o valor do primeiro número: ")
        fmt.Scanln(&num2) // aqui deveria ser num1
    
        fmt.Println("Digite o valor do segundo número: ")
        fmt.Scanln(&num2)
    
        menu()
        fmt.Scanln(&resposta)
        switch resposta {
        case 1:
            fmt.Println(soma)
        case 2:
            fmt.Println(subtracao)
        default:
            fmt.Println("Número inválido!")
        }
    
    }

Another thing you have to think about is that you are doing all the operations even though they are not necessary, which is a waste of processing. It would be more interesting to have operations inside the switch next to the result print.

  • Thanks man, this already gave me a light!

Browser other questions tagged

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