开发者

How to count amount of digits in a given number in c++

Count amount of digits 开发者_如何学JAVAin a given number or input by the user.


Independent of programming language:

floor(log10(x))+1

where x is your number (>0).

If you want to handle 0 and negative numbers, I'd suggest something like this:

x == 0 ? 1 : floor(log10(abs(x)))+1


Convert the number to a string and count the characters.


I assume you want to know how many base 10 digits do you need to represent a binary number (such as an int).

double x = something(positive); 
double base = 10.0; 
double digits = ceil(log(x + 1.0) / log(base));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜