Quadratic equation in Go
Example for versions
gc-2010-07-14
When you import several packages, you can put a dot before name of one of them, and use its functions without a package-name prefix, like fmt
in this example.
To read a number, one has to read a string from standard input, remove the trailing ‘n’ and convert it into the wanted format. In our case, input variables are integer, but further on we’ll be using them for floating-point calculations. Go doesn’t support implicit type conversions, so it’s better to parse input as float64 (the type of argument for math.Sqrt
) right away.
Assignment = is plain one, while := means that the variable on the left side is defined in this line. Note that defined but unused variables count as compilation errors, so you have to use err
in some way.
package main
import (
"os"
. "fmt"
"math"
"bufio"
"strconv")
func main() {
in := bufio.NewReader(os.Stdin)
line, err := in.ReadString('\n')
line = line[0 : len(line)-1]
A, err := strconv.Atof64(line)
if (A == 0) {
Print("Not a quadratic equation.")
return
}
line, err = in.ReadString('\n')
line = line[0 : len(line)-1]
B, err := strconv.Atof64(line)
line, err = in.ReadString('\n')
line = line[0 : len(line)-1]
C, err := strconv.Atof64(line)
if err != nil {
Print(err)
}
D := B*B-4*A*C
if (D == 0) {
Printf("x = %f", -B/2/A)
return
}
if (D>0) {
Printf("x1 = %f\nx2 = %f", -B/2/A + math.Sqrt(D)/2/A, -B/2/A - math.Sqrt(D)/2/A)
} else {
Printf("x1 = (%f, %f)\nx2 = (%f, %f)", -B/2/A, math.Sqrt(-D)/2/A, -B/2/A, -math.Sqrt(-D)/2/A)
}
}
Comments
]]>blog comments powered by Disqus
]]>