1. 程式人生 > >go 函式舉例練習

go 函式舉例練習

1. 求1到100之內的所有質數,並列印到螢幕上

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 之間所有的水仙花數

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.輸入一個字元,分別統計出其中英文字目、空格、數字和其它字元的個數

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) }