如何使用log10正确计算整数长度? [英] How does using log10 correctly calculate the length of a integer?

查看:288
本文介绍了如何使用log10正确计算整数长度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆