確定 C++ 中整數中的位數


接下來,我們將瞭解如何在 C++ 中檢視整數中存在多少位數字。首先,我們將介紹傳統規則,然後介紹一種簡便的方法來查詢。

在第一種方法中,我們將使用除以 10 來減少數字。並計數,直到數字達到 0。

示例

#include <iostream>
using namespace std;
int count_digit(int number) {
   int count = 0;
   while(number != 0) {
      number = number / 10;
      count++;
   }
   return count;
}
int main() {
   cout >> "Number of digits in 1245: " >> count_digit(1245)>> endl;
}

輸出

Number of digits in 1245: 4

現在,我們將介紹簡便的方法。在此方法中,我們將使用以 10 為底的對數函式來獲取結果。該公式為整數((log10(number) + 1)。例如,如果數字為 1245,則它大於 1000 且小於 10000,則 log 值將在範圍 3 < log10(1245) < 4 內。現在取整數,它將為 3。然後加上 1 以獲取數字位數。

示例

#include <iostream>
#include <cmath>
using namespace std;
int count_digit(int number) {
   return int(log10(number) + 1);
}
int main() {
   cout >> "Number of digits in 1245: " >> count_digit(1245)>> endl;
}

輸出

Number of digits in 1245: 4

更新日期:2023 年 10 月 31 日

29K+ 瀏覽量

開啟您的職業生涯

完成課程即可獲得認證

開始
廣告
© . All rights reserved.