美文网首页
第6章 函数

第6章 函数

作者: yezide | 来源:发表于2019-06-01 17:00 被阅读0次

    1、函数返回值

    package main
    
    import "fmt"
    
    var num int = 10;
    var rslt1, rslt2 int;
    var rslt3, rslt4 int;
    
    func main() {
        rslt1, rslt2 = getX2AndX3_1(num);
        fmt.Printf("num = %d, 2x num = %d, 3x num = %d\n", num, rslt1, rslt2)
        rslt3, rslt4 = getX2AndX3_2(num);
        fmt.Printf("num = %d, 2x num = %d, 3x num = %d\n", num, rslt3, rslt4)
    }
    
    func getX2AndX3_1(input int) (int, int) {
        return 2 * input, 3 * input;
    }
    
    /**
      * 这种方式尽量避免使用,代码可读性差
      */
    func getX2AndX3_2(input int) (rslt3 int, rslt4 int) {
        rslt3 = 2 * input;
        rslt4 = 3 * input;
        return
    }
    

    2、递归

    package main
    
    import "fmt"
    
    var num int = 10;
    var rslt1, rslt2 int;
    var rslt3, rslt4 int;
    
    func main() {
        
        for i := 0; i < 10; i++ {
            result := fibonacci(i);
            fmt.Printf("fibonacci(%d) is: %d\n", i, result);
        }
    }
    
    func fibonacci(n int) int {
        res := 0;
        if(n <= 1) {
            res = 1;
        } else {
            res = fibonacci(n-1) + fibonacci(n-2);
        }
        return res;
    }
    

    3、闭包

    package main
    
    import "fmt"
    
    func main() {
        funcAddBmp := MakeAddSuffix(".bmp");
        funcAddJpg := MakeAddSuffix(".jpg");
    
        fmt.Println("filename with bmp is ", funcAddBmp("rantu"));
        fmt.Println("filename whth jpg is ", funcAddJpg("9app"));
    }
    
    func MakeAddSuffix(suffix string) func(string) string {
        return func(name string) string {
            return name + suffix;
        }
    }
    

    5、 利用缓存实现fibonacci数列

    package main
    
    import "fmt"
    import "time"
    
    const LIMIT = 41;
    var fibs [LIMIT]uint64;
    
    func main() {
        var result uint64 = 0
        start := time.Now();
        for i := 0; i < LIMIT; i++ {
            result = fibonacci(i);
            fmt.Printf("fibonacci(%d) is: %d\n", i, result)
        }
        end := time.Now();
        durtion := end.Sub(start);
        fmt.Println("cost time :", durtion);
    }
    
    func fibonacci(n int) uint64 {
        var res uint64;
        if fibs[n] != 0 {
            return fibs[n];
        }
        if(n <= 1) {
            res = 1;
        } else {
            res = fibonacci(n-1) + fibonacci(n-2);
        }
        fibs[n] = res;
        return res;
    }
    

    相关文章

      网友评论

          本文标题:第6章 函数

          本文链接:https://www.haomeiwen.com/subject/myqsiqtx.html