dongling4288 2018-10-31 23:01
浏览 43

Golang简单用户输入产品数学问题,例如3 * 2 * 1 = 6

I'm trying to create a small program that allows a user to input an integer which will output the product such as follows:

For example:

a = 5, 5*4*3*2 = 120
a = 4, 4*3*2*1 = 24  
a = 3, 3*2*1 = 6

Can someone provide guidance as I'm stuck on how to frame this more efficiently. If using Python, I would probably write the logic something like:

def a(num):
    x = 1
    for i in range (num):
            x=x*(i + 1)
    return x

print a(5)
  • 写回答

2条回答 默认 最新

  • dousong2967 2018-11-01 03:27
    关注

    You need to learn about the go language itself first, after that you'll be able to convert your python code into go, easily.

    Few go learning resources:


    But anyway, here is the go version of your python code:

    func a(num int) int {
        x := 1
        for i := 0; i < num; i++ {
            x = x * (i + 1)
        }
        return x
    }
    
    func main() {
        fmt.Println(a(5)) // 120
        fmt.Println(a(4)) // 24
        fmt.Println(a(3)) // 6
    }
    

    Working playground: https://play.golang.org/p/glHwuMhTDYj

    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题