如何使用log10正确计算整数长度? [英] How does using log10 correctly calculate the length of a integer?
问题描述
int length = (int) floor( log10 (float) number ) + 1;
我的问题本质上是一个数学问题:为什么要取一个数字的log10(),对该数字取底,加1,然后将其强制转换为一个int来正确计算数字的长度?
My question is essentially a math question: WHY does taking the log10() of a number, flooring that number, adding 1, and then casting it into an int correctly calculate the length of number?
我真的很想知道更深的数学解释!
I really want to know the deep mathematical explanation please!
推荐答案
对于具有n
位数字的整数number
,其值在10^(n - 1)
(包括)和10^n
之间,因此log10(number)
在n - 1
(包括)和n
之间.然后,函数floor
减少小数部分,结果保留为n - 1
.最后,在其上添加1
即可得到位数.
For an integer number
that has n
digits, it's value is between 10^(n - 1)
(included) and 10^n
, and so log10(number)
is between n - 1
(included) and n
. Then the function floor
cuts down the fractional part, leaves the result as n - 1
. Finally, adding 1
to it gives the number of digits.
这篇关于如何使用log10正确计算整数长度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!