2
在K & R第71页中,atof函数使用数组索引。我试图使用指针算法实现相同的功能(因为它使感觉像一个坏蛋:))。K&R的这个实现有什么问题?
double atof(char *str)
{
int sign;
double number = 0.0, power = 1.0;
while(isspace(*str))
++str;
sign = (*str == '-') ? -1 : 1; // Save the sign
if(*str == '-' || *str == '+') // Skip the sign
str++;
while(isdigit(*str)) // Digits before the decimal point
{
number = 10.0 * number + (*str - '0');
str++;
}
if(*str == '.') // Skip the decimal point
str++;
while(isdigit(*str)) // Digits after the decimal point
{
number = 10.0 * number + (*str - '0');
power *= 10.0;
str++;
}
return sign * number/power;
}
在主
printf("%g\n", atof(" 123123.123")); // Outputs 123123
printf("%g\n", atof(" 1234.1222")); // Outputs 1234.12
什么是我的错!
该死的我应该知道的:)。那么%g的默认精度是6位数?! – MAA
是(包括*小数*和小数部分的总宽度)。 6是大多数printf精度的默认值。您可以在这里阅读C标准中的详细信息:http://port70.net/~nsz/c/c11/n1570.html#7.21.6.1p8 –
非常感谢你。特别是对于包括这个标准。 – MAA