C++ 获取int中的位数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11151548/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 14:53:48  来源:igfitidea点击:

Get the number of digits in an int

c++c

提问by user1417815

How do I detect the length of an integer? In case I had le: int test(234567545);

如何检测整数的长度?如果我有 le: int test(234567545);

How do I know how long the int is? Like telling me there is 9 numbers inside it???

我怎么知道 int 有多长?就像告诉我里面有 9 个数字???

*I have tried:**

*我试过了:**

char buffer_length[100];


    //  assign directly to a string.

    sprintf(buffer_length, "%d\n", 234567545);

    string sf = buffer_length;


    cout <<sf.length()-1 << endl;

But there must be a simpler way of doing it or more clean...

但是必须有一种更简单的方法或者更干净的方法......

回答by Luchian Grigore

How about division:

分工如何:

int length = 1;
int x = 234567545;
while ( x /= 10 )
   length++;

or use the log10method from <math.h>.

或使用 中的log10方法<math.h>

Notethat log10returns a double, so you'll have to adjust the result.

请注意log10返回 a double,因此您必须调整结果。

回答by Shehzad Bilal

Make a function :

做一个功能:

int count_numbers ( int num) {
   int count =0;
   while (num !=0) {   
      count++;  
      num/=10;
   } 
   return count;
}

回答by jmg

Nobody seems to have mentioned converting it to a string, and then getting the length. I'm not sure how performant this is, but it definitely does it in one line of code :)

似乎没有人提到将其转换为字符串,然后获取长度。我不确定它的性能如何,但它肯定是在一行代码中完成的 :)

int num = 123456;
int len = to_string(num).length();

cout << "LENGTH of " << num << " is " << len << endl;
// prints "LENGTH of 123456 is 6"

回答by Thorsen

if "i" is the integer, then

如果“i”是整数,那么

int len ;

char buf[33] ;

itoa (i, buf, 10) ; // or maybe 16 if you want base-16 ?

len = strlen(buf) ;

if(i < 0)
    len-- ;    // maybe if you don't want to include "-" in length ?

回答by Sanish

You can use stringstreamfor this as shown below

您可以使用stringstream如下所示

stringstream ss;
int i = 234567545;
ss << i;
cout << ss.str().size() << endl;

回答by A_nto2

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() {

    int i=2384995;
    char buf[100];

    itoa(i, buf, 10); // 10 is the base decimal

    printf("Lenght: %d\n", strlen(buf));


    return 0;
}

Beware that itoa is not a standard function, even if it is supported by many compilers.

请注意 itoa 不是标准函数,即使它被许多编译器支持。

回答by Anonymous

looking across the internet it's common to make the mistake of initializing the counter variable to 0 and then entering a pre-condition loop testing for as long as the count does not equal 0. a do-while loop is perfect to avoid this.

在互联网上查看,很常见的错误是将计数器变量初始化为 0,然后只要计数不等于 0,就进入一个前置条件循环测试。do-while 循环是完美的避免这种情况。

    unsigned udc(unsigned u) //unsigned digit count
    {
      unsigned c = 0;
      do
        ++c;
      while ((u /= 10) != 0);
      return c;
    }

it's probably cheaper to test whether uis less than 10to avoid the uneccessary division, increment, and cmp instructions for cases where u< 10.

u< 10 的情况下,为了避免不必要的除法、增量和 cmp 指令,测试u是否小于10可能更便宜。

but while on that subject, optimization, you could simply test uagainst constant powers of ten.

但是在优化这个主题上,您可以简单地用10 的常数幂测试u

    unsigned udc(unsigned u) //unsigned digit count
    {
      if (u < 10)   return 1;
      if (u < 100)  return 2;
      if (u < 1000) return 3;
      //...
      return 0; //number was not supported
    }

which saves you 3instructions per digit, but is less adaptable for different radixes inaddition to being not as attractive, and tedious to write by hand, in which case you'd rather write a routine to write the routine before inserting it into your program. because C only supports very finite numbers, 64bit,32bit,16bit,8bit, you could simply limit yourself to the maximum when generating the routine to benefit all sizes.

这为每个数字节省了3条指令,但对不同基数的适应性较差,除了不那么有吸引力,而且手工编写很乏味,在这种情况下,您宁愿编写一个例程来编写例程,然后再将其插入到您的程序中。因为 C 只支持非常有限的数字,64bit32bit16bit8bit,你可以简单地将自己限制在最大时生成例程以受益所有大小。

to account for negative numbers, you'd simply negateuif u< 0before counting the number of digits. of course first making the routine support signednumbers.

考虑到负数,如果u< 0,您只需在计算位数之前否定u。当然首先制作常规支持签名数字。

if you know that u< 1000, it's probably easier to just write, instead of writing the routine.

如果您知道u< 1000,那么直接编写可能更容易,而不是编写例程。

   if (u > 99) len = 3;
   else
   if (u > 9)  len = 2;
   else        len = 1;

回答by congar

len=1+floor(log10(n));//c++ code lib (cmath)

len=1+floor(log10(n));//c++代码库(cmath)