Golang之函數練習

小例題:html

package main

import "fmt"

/*
函數練習,
可變參數使用

寫一個函數add 支持1個或多個int相加,並返回相加結果
寫一個函數concat,支持1個或多個string拼接,並返回結果
 */
func add(a int, arg ...int) int {
    sum := a
    for i := 0; i < len(arg); i++ {
        sum += arg[i]
    }
    return sum
}

func concat(a string, arg ...string) (result string) {
    result = a
    for i := 0; i < len(arg); i++ {
        result += arg[i]
    }
    return
}

func main() {
    sum := add(10, 3, 3, 3, 3, 3)
    fmt.Println(sum)
    res:=concat("hello"," ","大屌")
    fmt.Println(res)
}

 九九乘法表:golang

package main

import "fmt"
//99乘法表
func multi() {
    for i := 0; i < 9; i++ {
        for j := 0; j <= i; j++ {
            fmt.Printf("%d*%d=%d\t", (i + 1), j+1, (i+1)*(j+1))
        }
        fmt.Println()
    }

}
func main() {
    multi()

}

 檢測迴文(中文):ide

package main

import (
    "fmt"
)

func process(str string) bool {
    t := []rune(str)
    length := len(t)
    for i, _ := range t {
        if i == length/2 {
            break
        }
        last := length - i - 1
        if t[i] != t[last] {
            return false
        }
    }
    return true
}
func main() {
    var str string
    fmt.Scanf("%sd", &str)
    if process(str) {
        fmt.Println("yes")
    } else {
        fmt.Println("no")
    }
}

 統計一段字符串,中文,字符,數字,空格,出現的次數:函數

package main

import (
    "bufio"
    "fmt"
    "os"
)

func count(str string) (wordCount, spaceCount, numberCount, otherCount int) {
    t := []rune(str)
    for _, v := range t {
        switch {
        case v >= 'a' && v <= 'z':
            fallthrough
        case v >= 'A' && v <= 'Z':
            //golang裏面++是語句,不能寫成表達式
            wordCount++
        case v == ' ':
            spaceCount++
        case v >= '0' && v <= '9':
            numberCount++
        default:
            otherCount++
        }
    }
    return
}

func main() {
    reader := bufio.NewReader(os.Stdin)
    result, _, err := reader.ReadLine()
    //若是錯誤不爲空,說明有錯,就報錯
    if err != nil {
        fmt.Println("read from console err:", err)
        return
    }
    wc,sc,nc,oc:=count(string(result))
    fmt.Printf("word Count:%d\n space count:%d\n number count:%d\n others count:%d\n",wc,sc,nc,oc)
}
相關文章
相關標籤/搜索