如何在C/C ++中最多计算1000位数字中的位数 [英] How can I count the number of digits in a number up to 1000 digits in C/C++
本文介绍了如何在C/C ++中最多计算1000位数字中的位数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何计算C或C ++中最多1000个数字的位数
#include <stdio.h>
int main()
{
int num,counter=0;
scanf("%d",&num);
while(num!=0){
num/=10;
counter++;
}
printf("%d\n",counter);
}
此代码仅适用于最多10位数字-我不知道为什么.
This code works just for numbers up to 10 digits — I don't know why.
推荐答案
由于大多数计算机无法容纳1000个数字的整数,因此您将不得不对输入进行字符串操作或使用 Big数字库.让我们尝试前者.
Since most computers can't hold an integer that is 1000 digits, you will either have to operate on the input as a string or use a Big Number library. Let's try the former.
当将输入视为字符串时,每个数字都是一个介于'0'
到'9'
(含)范围内的字符.
When treating the input as a string, each digit is a character in the range of '0'
to '9'
, inclusive.
因此,这归结为计数字符:
So, this boils down to counting characters:
std::string text;
cin >> text;
const unsigned int length = text.size();
unsigned int digit_count = 0;
for (i = 0; i < length; ++i)
{
if (!std::isdigit(text[i]))
{
break;
}
++digit_count;
}
cout << "text has " << digit_count << "digits\n";
这篇关于如何在C/C ++中最多计算1000位数字中的位数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文