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
-
\$\begingroup\$ I'm quite new to programming and completely new to Golang. I hope this awesome community will help me polish my skills. \$\endgroup\$Cute Tom– Cute Tom2016年08月06日 08:29:57 +00:00Commented Aug 6, 2016 at 8:29
1 Answer 1
No sense send slice of numbers into the summation function. Would be better pass the string and work with it. This will avoid necessary enumeration of the elements of the slice and return result.
No need to create a slice with 0 capacity,because it will increase costly. In your case, it was possible to write so:
floatsSlice := make([]float64, len(textSlice))
...
for index, elem := range textSlice {
...
floatsSlice[index] = i
}
No need to create extra variable
fmt.Println("Here is the result:", AddAll(ReadInput()))
Putting it all together and the result is:
func getline() (string, error) {
return bufio.NewReader(os.Stdin).ReadString('\n')
}
func sumNumbers(str string) float64 {
var sum float64
for _, v := range strings.Fields(str) {
i, err := strconv.ParseFloat(v, 64)
if err != nil {
fmt.Println(err)
} else {
sum += i
}
}
return sum
}
Call:
str, err := getline()
if err == nil {
fmt.Println("Here is the result:", sumNumbers(str))
}
-
\$\begingroup\$ I think you mean
if err == nil
for that last check before printing the sum. \$\endgroup\$David Harkness– David Harkness2016年08月16日 19:41:25 +00:00Commented Aug 16, 2016 at 19:41