D
D
Denis2021-08-07 14:55:19
go
Denis, 2021-08-07 14:55:19

How to convert the data type correctly?

I am new to Golang, learning the second day. I decided to make a simple calculator for practice, but something doesn’t work out very well.

Here is the code for the calculator itself:

package main

import (
  "fmt"
  "os"
)

func main() {

  var what string
  var a float64
  var b float64

  fmt.Print("Выберите действие (+, -)")
  fmt.Fscan(os.Stdin, &what)

  fmt.Print("Введите первое значение: ")
  fmt.Fscan(os.Stdin, &a)

  fmt.Print("Введите второе значение: ")
  fmt.Fscan(os.Stdin, &b)

  var c float64
  if what == "+" {
    c = a + b
    fmt.Println("Результат: " + c)
  } else if what == "-" {
    c = a - b
    fmt.Println("Результат: " + c)
  }
}


Error:
# command-line-arguments
.\calc.go:26:38: cannot use "Result: " (type untyped string) as type float64
.\calc.go:29:38: cannot use "Result: " (type untyped string) as type float64

When I try to convert variable "c" to string, I get another error:
# command-line-arguments
.\calc.go:26:38: cannot use "Result: " (type untyped string) as type float64
.\calc.go:29:38: cannot use "Result: " (type untyped string) as type float64

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Evgeny Mamonov, 2021-08-07
@cod1x_dev

When you read data from the console, it comes to you as a string.
Those. first you need to read it into a string, and then you need to convert the string to a float.
Here is a working example

package main

import (
    "fmt"
    "log"
    "os"
    "strconv"
)

func main() {

    var what string
    var input string

    fmt.Print("Выберите действие (+, -)")
    fmt.Fscan(os.Stdin, &what)
    if what != `+` && what != `-` {
        log.Fatalf("действие указанно не корректно\n")
    }

    fmt.Print("Введите первое значение: ")
    fmt.Fscan(os.Stdin, &input)
    a, err := strconv.ParseFloat(input, 64)
    if err != nil {
        log.Fatalf("число указано не корректно: %v\n", err)
    }

    fmt.Print("Введите второе значение: ")
    fmt.Fscan(os.Stdin, &input)
    b, err := strconv.ParseFloat(input, 64)
    if err != nil {
        log.Fatalf("число указано не корректно: %v\n", err)
    }

    var c float64
    if what == "+" {
        c = a + b
    } else if what == "-" {
        c = a - b
    }

    fmt.Printf("Результат: %v\n", c)
}

If these are your first steps in programming, it is better to start with Python, it will significantly simplify the start.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question