练习4.2:对atof函数进行扩充,使他可以处理形如123.45e-6的科学表示法。
long double atof(char s[]){//不考虑e6.5这种指数里有小数的情况了,缺点是没有差错处理。同时超过long double的精度时,会失去部分数据。
long double val, power;
int i, sign,esign, eval;
long power1 = 1;
for (i = 0;isspace(s[i]);i++) {//跳过空格
;
}
sign = (s[i] == '-') ? -1:1;
if (s[i] == '+' || s[i] == '-') {
i++;
}
for (val = 0.0;isdigit(s[i]);i++) {
val = 10.0*val + (s[i] - '0');
}
if (s[i]=='.')
{
i++;
for (power=1.0;isdigit(s[i]) ; i++)
{
val = 10.0*val + (s[i] - '0');
power *= 10.0;
}
val = val / power;
}
if (s[i]=='e')
{
i++;
esign = (s[i] == '-') ? -1 : 1;
if (s[i]=='-')
{
i++;
}
for (eval = 0.0;isdigit(s[i]);i++) {
eval = eval * 10.0 + (s[i] - '0');
}
for (double n=0.0;n < eval; n++)
{
power1 = power1 * 10;
}
}
if (esign==-1)
{
return sign*val / power1;
}
else
{
return sign*val*power1;
}
}