如何计算一个浮点数由多少数字组成?
想了好久,没想出答案,结果听门外者(完全不懂编程)说了一个思路,瞬间开朗。
#define EPS 1e-12
unsigned int getIntegerLength(long long l)
{
long long temp = 10l;
unsigned int len = 1;
while (l/temp != 0)
{
temp = temp * 10l;
len++;
}
return len;
}
unsigned int getDoubleLength(double d)
{
long long high = (long long)d;
double low = d - high;
unsigned int len = getIntegerLength(high);
double temp = low, a = 0.1;
while (low > EPS)
{
low -= a * (long long)(temp * 10l);
a /= 10.0;
temp = temp * 10 - (long long)(temp*10);
len++;
}
return len+1;
}
注意:有精度误差。
一个问题,longlong 在所有平台都会保证64位吗?