简体   繁体   中英

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

计算给定数字或用户输入的位数。

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

将数字转换为字符串并计算字符。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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