Reputation: 1355
In K&R page 71, the atof function is using array indexing. I am trying to implement the same function using pointer arithmetic(Because it makes feel like a badass :)).
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;
}
In main
printf("%g\n", atof(" 123123.123")); // Outputs 123123
printf("%g\n", atof(" 1234.1222")); // Outputs 1234.12
What's my mistake ?!
Upvotes: 2
Views: 331
Reputation: 121407
The atof()
implementation is fine. But printf with %g
removes parts of the result.
6
is the default if you don't explicitly specify it. Since the resulting value has greater precision, it's lost. Specify the precision:
printf("%.12g\n", atof(" 123123.123"));
printf("%.12g\n", atof(" 1234.1222"));
Or alternatively, you can use %f
(which would print trailing zeros though).
Upvotes: 4