The following Golang code accepts a sequence of numbers (any integer and float type) in the terminal, adds them, and prints the result (sum) to the terminal.
Actually in Golang you can't add different integer types together, because of which this script accepts all the digits as a string representation of space-separated digits, then splits it on the spaces into int64 digits. It then sums all of the digits and writes the result to the terminal.
Is there any way to improve this code?
package main
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)
func main() {
a := ReadInput()
fmt.Println("Here is the result:", AddAll(a))
}
func ReadInput() []float64 {
reader := bufio.NewReader(os.Stdin)
fmt.Println("Enter digits to be added (space separated): ")
text, err := reader.ReadString('\n')
if err != nil {
fmt.Println(err)
}
textSlice := strings.Fields(text)
floatsSlice := make([]float64, 0)
for _, elem := range textSlice {
i, err := strconv.ParseFloat(elem, 64)
if err != nil {
fmt.Println(err)
}
floatsSlice = append(floatsSlice, i)
}
return floatsSlice
}
func AddAll(floatsSlice []float64) float64 {
var sum float64
for _, v := range floatsSlice {
sum += v
}
return sum
}
For example if we enter the following,
1 2.3345 2.5 3.3 8.9 0.5 23
The output will be 41.5345