How to use log10 correctly to calculate integer length?

int length = (int) floor( log10 (float) number ) + 1;

My question is essentially a mathematical question: WHY takes log10 () of a number, typing that number, adding 1, and then inserting it into int, correctly calculating the length of the number?

I really want to know a deep mathematical explanation, please!

+4
source share
2 answers

For an integer numberthat has digits n, this value is between 10^(n - 1)(included) and 10^n, therefore, log10(number)is between n - 1(included) and n. Then the function floorreduces the fractional part, leaves the result as n - 1. Finally, adding to it 1gives the number of digits.

+7

, x - 1000 <= x < 10000. - 10 , 3.000 <= log(x, 10) < 4.000. ( int) , 4 <= int(log(x, 10))+1 <= 4.

, x.

+6

Source: https://habr.com/ru/post/1544266/


All Articles