确定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,因此对数值将在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
热门推荐
10 财运虎年祝福语简短语
11 单亲爸爸春节祝福语简短
12 狗狗上厕所训练
13 植物种植祝福语简短
14 翻译考试祝福语朋友简短
15 个人周年庆简短祝福语
16 狗狗怎么训练
17 分别祝福语简短搞笑英文
18 生日广州男生祝福语简短