dongmoxin7111 2017-01-02 05:31
浏览 16
已采纳

这是计算器程序,如何为未知数量的输入编码?

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))
}
  • 写回答

2条回答 默认 最新

  • dtyqeoc70733 2017-01-02 05:57
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里