7
\$\begingroup\$

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

200_success
146k22 gold badges190 silver badges479 bronze badges
asked Aug 6, 2016 at 7:58
\$\endgroup\$
1
  • \$\begingroup\$ I'm quite new to programming and completely new to Golang. I hope this awesome community will help me polish my skills. \$\endgroup\$ Commented Aug 6, 2016 at 8:29

1 Answer 1

4
\$\begingroup\$
  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.

  2. 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 }

  1. 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))
}
answered Aug 6, 2016 at 12:10
\$\endgroup\$
1
  • \$\begingroup\$ I think you mean if err == nil for that last check before printing the sum. \$\endgroup\$ Commented Aug 16, 2016 at 19:41

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.