golang初识1

1. 功能块(function block)

    格式:

func function_name( [parameter list] ) [return_types] {
   //body
}

    与delphi的异同:

(1)关键字

   Delphi: procedure 和 function

   Go: 使用一个func替代以上2个。

(2)参数列表

    Delphi: 使用冒号(:)来声明

    Go:省略冒号(:)

(3)返回值

    Delphi:使用冒号(:)来声明,并且只能返回一个!

    Go:省略冒号(:),而且能返回多个(牛X的一点)

src:termial_factorial.go

package main

import (
    "fmt"
    "os"
    "strconv"
)

func main() {
    input, err := strconv.Atoi(os.Args[1])
    if err != nil {
        fmt.Println(err)
    }
    x, y := mul_add(input)
    fmt.Println("阶加", input, "=" ,x, "
阶乘,累加", input, "=", y)
}

func mul_add(n int) (int, int) {
    var tmp int
    input1, input2 := n, n

    // 赋初值
    ret1, ret3 := 0, 0
    ret2 := 1

    for input1 > 0 {
        ret1 = ret1 + input1
        input1--
    }

    // n! + ... + 3! + 2! + 1!;
    for input2 > 0 {
        tmp = input2
        for tmp > 1 {
            ret2 = ret2 * tmp
            tmp--
        }
    
        ret3 = ret3 + ret2
        ret2 = 1
        input2--
    }
    return ret1, ret3
}

exec:

go run termial_factorial.go 9
原文地址:https://www.cnblogs.com/xiaobin-hlj80/p/10670454.html