如何在 C/C++ 中计算一个数字中的位数,最多 1000 位

How can I count the number of digits in a number up to 1000 digits in C/C++

本文关键字:数字 一个 1000 最多 C++ 计算      更新时间:2023-10-16

如何在 C 或 C++ 中计算一个数字中的位数,最多 1000 位

#include <stdio.h>
int main()
{
    int num,counter=0;
    scanf("%d",&num);
    while(num!=0){
        num/=10;
        counter++;
    }
    printf("%dn",counter);
}

此代码仅适用于最多 10 位数字的数字——我不知道为什么。

由于大多数计算机无法容纳 1000 位整数,因此您必须将输入作为字符串进行操作,或者使用大数库。 让我们试试前者。

将输入视为字符串时,每个数字都是 '0''9' 范围内的字符(包括 到 (。

因此,这归结为计算字符数:

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 << "digitsn";
相关文章: