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 质数
", 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 是水仙花数
", 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 
 spaceCount=%d 
 numCount=%d 
 otherCount=%d 
", charCount, spaceCount, numCount, otherCount)
}
原文地址:https://www.cnblogs.com/ctztake/p/10262085.html