简体   繁体   English

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

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

How can I count the number of digits in a number up to 1000 digits in C or C++ 如何在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);
}

This code works just for numbers up to 10 digits — I don't know why. 该代码仅适用于最多10位数字-我不知道为什么。

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. 由于大多数计算机不能容纳1000个数字的整数,因此您将不得不对输入进行字符串操作或使用Big Number库。 Let's try the former. 让我们尝试前者。

When treating the input as a string, each digit is a character in the range of '0' to '9' , inclusive. 将输入视为字符串时,每个数字都是一个介于'0''9'范围内的字符。

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";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM