简体   繁体   English

如何在C ++中计算给定数字中的位数

[英]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). 其中x是您的数字(> 0)。

If you want to handle 0 and negative numbers, I'd suggest something like this: 如果您想处理0和负数,我建议使用以下方法:

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). 我假设您想知道代表一个二进制数字(例如int)需要多少个基数为10的数字。

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

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

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