go 函數舉例練習

1. 求1到100以內的全部質數,並打印到屏幕上spa

package main

import "fmt"

// 求1-100 內的質數
func justfy(i int) bool {
    if i <= 1 {
        return false
    }

    for j := 2; j <= i/2; j++ {
        if i%j == 0 {
            return false
        }
    }

    return true
}

func exp() {
    for i := 1; i <= 100; i++ {
        if justfy(i) {
            fmt.Printf("%d is 質數\n", i)
        }
    }
}

func main() {
    exp()
}

2. 求出 100-999 之間全部的水仙花數code

package main

import "fmt"

func issxh(i int) bool {
    ge := i % 10
    shi := (i / 10) % 10
    bai := i / 100

    sum := ge*ge*ge + shi*shi*shi + bai*bai*bai

    if sum == i {
        return true
    } else {
        return false
    }

}

func exp() {
    for i := 100; i <= 999; i++ {
        if issxh(i) {
            fmt.Printf("%d 是水仙花數\n", i)
        }
    }
}

func main() {
    // fmt.Println(111 / 10)
    exp()
}

3.輸入一個字符,分別統計出其中英文字目、空格、數字和其它字符的個數blog

package main

import "fmt"

// 求一個字符串中英文個數  空格個數 數字個數 其餘個數
// 字符串用雙引號 字符 用單引號
func counttest(str string) (charCount, spaceCount, numCount, otherCount int) {
    utf8_str := []rune(str)
    for i := 0; i < len(utf8_str); i++ {
        if (utf8_str[i] >= 'a' && utf8_str[i] <= 'z') || (utf8_str[i] >= 'A' && utf8_str[i] <= 'Z') {
            charCount++
            continue
        } else if utf8_str[i] == ' ' {
            spaceCount++
            continue
        } else if utf8_str[i] >= '0' && utf8_str[i] <= '9' {
            numCount++
            continue
        } else {
            otherCount++
            continue
        }
    }
    return
}

func main() {
    str := "yunnan  is beautiful 雲南歡迎你 123"
    charCount, spaceCount, numCount, otherCount := counttest(str)
    fmt.Printf("charCount = %d \n spaceCount=%d \n numCount=%d \n otherCount=%d \n", charCount, spaceCount, numCount, otherCount)
}
相關文章
相關標籤/搜索