Search code examples
catof

atof() in K&R book 4.2


I'm exercising atof() which is provided in K&R book 4.2. However, when I compile the following code, I get

1952.690000

instead of

1237.88

I tried, but still don't know where's wrong. Maybe there is a problem with type conversions?

#include <stdio.h>
#include <ctype.h>

double atof(char s[]) {
  int i, sign;
  double n, power;

  for (i = 0; isspace(s[i]); ++i)
    ;

  sign = (s[i] == '-') ? -1 : 1;
  if (s[i] == '-' || s[i] == '+')
    ++i;

  for (n = 0.0; isdigit(s[i]); ++i)
    n += n * 10.0 + s[i] - '0';

  if (s[i] == '.')
    ++i;
  for (power = 1.0; isdigit(s[i]); ++i) {
    n += n * 10.0 + s[i] - '0';
    power *= 10.0;
  }

  return sign * n / power;
}

int main() {
  char s[] = "1237.88";

  printf("%lf", atof(s));

  return 0;
}

Solution

  • It seems you're not understanding the combined assignment operator well.

    Here's the error in your code:

    n+=n*10.0+s[i]-'0';
     ^^
    

    Note it's +=, add-and-assign. Based on the code I deduce that it's not what you intended to do. You should instead change it to a regular assignment operator:

    n = n*10.0+s[i]-'0';
      ^
    

    And the result is correct.

    For the other question in the comments in your code:

    // Why there is no need to set sign as a double?
    

    You can of course do it and you won't observe any difference in the results, so there is no need to do it (not you can't do it). It simply adds nothing to the code.