如何检测整数的长度?如果我有 le: int test(234567545);
我怎么知道 int 有多长?就像告诉我里面有9个数字???
*我试过了:**
char buffer_length[100];
// assign directly to a string.
sprintf(buffer_length, "%d\n", 234567545);
string sf = buffer_length;
cout <<sf.length()-1 << endl;
但必须有更简单或更干净的方法......
最佳答案
除法怎么样:
int length = 1;
int x = 234567545;
while ( x /= 10 )
length++;
或使用 log10
中的 <math.h>
方法。
注意 log10
返回一个 double
,因此您必须调整结果。
关于c++ - 获取 int 中的位数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11151548/