codinggirl
codinggirl

Reputation: 159

This is Calculator Program, How to code for unknown number of inputs?

This program is to do different calculations.right now it is only doing the basic operations for two numbers given in main, I'm trying to upgrade it to calculate for more than 2 numbers and more like for unknown number of number given in input.

package main

import (
    "fmt"
)

func add (n int , m int) int {
     sum := n + m
     return sum
}
func sub (n int , m int) int {
     diff := n - m
     return diff
}
func mul (n float32 , m float32) float32 {
     pro := n * m
     return pro
}

func div (n float32 , m float32) float32 {
     quo := n / m
     return quo
}

func main() {
    fmt.Println(add(4,6))
    fmt.Println(sub(4,6))
    fmt.Println(mul(4,6))
    fmt.Println(div(6,4))
}

Upvotes: 2

Views: 392

Answers (2)

1lann
1lann

Reputation: 667

Your question isn't too clear, so I'm going to make some assumptions. I'm assuming you want something that can do add(1, 2, 3) that will return 1 + 2 + 3.

There are two ways of doing this, either using slices, or using the ...T argument type. (Refer to the Go specifications).

An implementation that makes use of slices will accept a slice of numbers, and then use iterative methods to perform actions on the slice. For example for an add function:

func add(numbers []int) int {
    sum := 0
    for _, number := range numbers {
        sum += number
    }
    return sum
}

You can then call it like add([]int{1, 2, 3}) which will return the result of 1 + 2 + 3.

Using the ...T argument type is almost the same, as it basically turns multiple arguments into a slice.

func add(numbers ...int) int {
    sum := 0
    for _, number := range numbers {
        sum += number
    }
    return sum
}

Except calling it becomes different. Either: add(1, 2, 3) or if you would still like to use a slice, add([]int{1, 2, 3}...).

You should be able to apply these concepts to your other operations.

Upvotes: 0

Sarath Sadasivan Pillai
Sarath Sadasivan Pillai

Reputation: 7091

You may use ... to accept arbitery number of arguements, Here is how your program will be then

package main

import (
    "fmt"
)

func add(m ...int) int {
    sum := 0
    for _, i := range m {
        sum += i
    }
    return sum
}
func sub(m ...int) int {
    sub := m[0]
    for _, i := range m[1:] {
        sub -= i
    }
    return sub
}
func mul(m ...float32) float32 {
    c := float32(1)
    for _, i := range m {
        c *= i
    }
    return c
}
func div(m ...float32) float32 {
    quo := m[0]
    for _, i := range m[1:] {
        quo /= i
    }
    return quo
}

func main() {
    fmt.Println(add(4, 6))
    fmt.Println(sub(4, 6))
    fmt.Println(mul(4, 6))
    fmt.Println(div(6, 4))
}

Here is go play link : https://play.golang.org/p/dWrMa-GdGj

Upvotes: 2

Related Questions