Go程序计算数字中的位数

使用for循环编写一个Go程序来计算数字中的位数。for循环条件(num > 0)确保数字大于零。在循环中,我们递增计数器的值。接下来,我们将数字除以十(num = num / 10),这将从数字中移除最后一位。

package main

import "fmt"

func main() {

    var num, count int
    count = 0

    fmt.Print("Enter any number to count digits = ")
    fmt.Scanln(&num)

    for num > 0 {
        num = num / 10
        count = count + 1
    }
    fmt.Println("The total Number to Digits = ", count)
}
SureshMac:GoExamples suresh$ go run countDigits1.go
Enter any number to count digits = 46782
The total Number to Digits =  5
SureshMac:GoExamples suresh$ go run countDigits1.go
Enter any number to count digits = 657
The total Number to Digits =  3
SureshMac:GoExamples suresh$ 

Golang程序计算数字中的位数

在这个Golang示例中,我们修改了for循环,计算了用户输入值的总位数。

package main

import "fmt"

func main() {

    var num, count int

    fmt.Print("Enter any number to count digits = ")
    fmt.Scanln(&num)

    for count = 0; num > 0; num = num / 10 {
        count = count + 1
    }
    fmt.Println("The total Number to Digits = ", count)
}
SureshMac:GoExamples suresh$ go run countDigits2.go
Enter any number to count digits = 560986
The total Number to Digits =  6
SureshMac:GoExamples suresh$ go run countDigits2.go
Enter any number to count digits = 23
The total Number to Digits =  2
SureshMac:GoExamples suresh$ 

使用函数计算数字中位数的Go示例

package main

import "fmt"

func digitCount(num int) int {
    var count int = 0
    for num > 0 {
        num = num / 10
        count = count + 1
    }
    return count
}

func main() {

    var num, count int

    fmt.Print("Enter any number to count digits = ")
    fmt.Scanln(&num)

    count = digitCount(num)
    fmt.Println("The total Number to Digits = ", count)
}
SureshMac:GoExamples suresh$ go run countDigits3.go
Enter any number to count digits = 2345
The total Number to Digits =  4
SureshMac:GoExamples suresh$ go run countDigits3.go
Enter any number to count digits = 987
The total Number to Digits =  3
SureshMac:GoExamples suresh$ 

在这个Go 程序中,我们通过调用digitCount(num / 10)函数并传入更新后的值来递归地计算数字中的位数。

package main

import "fmt"

var count int = 0

func digitCount(num int) int {
    if num > 0 {
        count = count + 1
        digitCount(num / 10)
    }
    return count
}

func main() {

    var num int

    fmt.Print("Enter any number to count digits = ")
    fmt.Scanln(&num)

    count = digitCount(num)
    fmt.Println("The total Number to Digits = ", count)
}
Golang Program to Count Digits in a Number