确定 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程语言
C++
C#
MongoDB
MySQL
Javascript
PHP