Golang : Quadratic example
Here is a simple tutorial on how to perform quadratic calculation with Golang. This program accepts two floating point values from the command line and calculate the roots using quadratic formula. It also checks for the input values to see if they are floats or not.
Here you go!
package main
import (
"fmt"
"math"
"os"
"strconv"
)
func main() {
b, err := strconv.ParseFloat(os.Args[1], 10)
if err != nil {
fmt.Println("First input parameter must be of type float")
os.Exit(1)
}
c, err := strconv.ParseFloat(os.Args[2], 10)
if err != nil {
fmt.Println("Second input parameter must be of type float")
os.Exit(1)
}
fmt.Println("b : ", b)
fmt.Println("c : ", c)
// calculate the roots of the polynomial
// x^2 + bx + c using the quadratic formula
discriminant := b*b - 4.0*c
d := math.Sqrt(discriminant)
fmt.Printf("%0.6f\n", ((-b + d) / 2.0))
fmt.Printf("%0.6f\n", ((-b - d) / 2.0))
}
Sample output:
$./quadratic -1.0 -1.0
b : -1
c : -1
1.618034
-0.618034
$ ./quadratic -3.0 2.0
b : -3
c : 2
2.000000
1.000000
References:
https://www.socketloop.com/references/golang-strconv-parsefloat-function-example
https://www.socketloop.com/tutorials/golang-how-to-check-if-input-from-os-args-is-integer
https://www.socketloop.com/tutorials/golang-get-command-line-arguments
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+9.4k Golang : Eroding and dilating image with OpenCV example
+24.9k Golang : Get current file path of a file or executable
+7.7k Golang : Grayscale Image
+4.6k Golang : A program that contain another program and executes it during run-time
+19.7k Golang : Reset or rewind io.Reader or io.Writer
+11.7k Golang : How to parse plain email text and process email header?
+10.8k Golang : Calculate Relative Strength Index(RSI) example
+12.6k Golang : Convert IPv4 address to packed 32-bit binary format
+33.3k Golang : All update packages with go get command
+30.1k Golang : How to redirect to new page with net/http?
+5.6k CodeIgniter/PHP : Remove empty lines above RSS or ATOM xml tag
+13.8k Golang : Fix image: unknown format error