golang初識1 - func

 

1. 功能塊(function block)git

    格式:github

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

    與delphi的異同:spa

(1)關鍵字code

   Delphi: procedure 和 functionblog

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

(2)參數列表input

    Delphi: 使用冒號(:)來聲明it

    Go:省略冒號(:)io

(3)返回值ast

    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, "\n階乘,累加", 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
相關文章
相關標籤/搜索