Golang程序 计算数字中的位数
假设数字是:123456
所给数字的位数是:6
要计算一个数字的位数,我们可以采取以下方法
步骤
- 取整数的值并存储在一个变量中。
- 使用while循环,获取数字的每一位,并在每次获取数字时增加计数。
- 打印给定的整数中的数字。
例子
package main
import "fmt"
func main(){
var n int
fmt.Print("Enter the number: ")
fmt.Scanf("%d", &n)
count := 0
for n >0 {
n = n/10
count++
}
fmt.Printf("The number of digits in the given number is: %d", count)
}
输出
Enter the number: 123456
The number of digits in the given number is: 6