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

更新於: 31-7-2021

3K+ 瀏覽

開啟你的 職業生涯

完成課程以獲得認證

開始學習
廣告
© . All rights reserved.