Answer the question
In order to leave comments, you need to log in
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)
}
}
Answer the question
In order to leave comments, you need to log in
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)
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question