HiveBrain v1.2.0
Get Started
← Back to all entries
patterngoMinor

Sum numbers input from terminal

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
terminalnumbersinputsumfrom

Problem

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

Solution

-
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))
}

Code Snippets

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
}
str, err := getline()
if err == nil {
    fmt.Println("Here is the result:", sumNumbers(str))
}

Context

StackExchange Code Review Q#137983, answer score: 4

Revisions (0)

No revisions yet.