3

I'm studying K&R book. I'm currently at chapter 4. I was reading the atof() function on page 71. Function atof(s) converts string to its double precision floating point equivalent.

The code of atof() is as following:
//atof: convert string s to double

double atof2(char s[])
{
   double val, power;
   int i, sign;

   for (i = 0; isspace(s[i]); ++i) //skip white space
       ;
   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;
   }

   return sign * val / power;

}

My question is about variable: power. Why do we need it for?

I do understand the use of variable: "val" but i'm not sure about variable: "power". Why do we divide val by power?

Lundin
  • 195,001
  • 40
  • 254
  • 396
Hussein Barada
  • 117
  • 1
  • 11

1 Answers1

5

Variable power is for division of number by power , to get result as float point .

Let your string be -12.83 , then first for loop will check for space and increment i as no space so ,i=0 .

sign will be -1 as s[i]=s[0]='-' .

In next two loops string's values are converted to integers and stored in val ( excluding . - figure out yourself) .

Now after both loop val will be 1283 . But last loop will iterate for 2 times and power will be changed to 100.00 (10*1.0 in first iteration and 10*10.0 in second iteration) .

Now to get value as float point val is divided by power and multiplied by sign .

So , what it will return is -1*1283/100 , thus -12.83 is your float point number .

ameyCU
  • 16,489
  • 2
  • 26
  • 41
  • Ok. But why they used two loops: 1) for (val = 0.0; isdigit(s[i]); i++) val = 10.0 * val + (s[i] - '0'); and 2) for (power = 1.0; isdigit(s[i]); i++) { val = 10.0 * val + (s[i] - '0'); power *= 10.0; } Can't we simply merge both for loops in one loop as follows: for (val = 0.0, power = 1.0; isdigit(s[i]); i++) { val = 10.0 * val + (s[i] - '0'); power *= 10.0; } I hope i made my question clear? – Hussein Barada Oct 21 '15 at 12:03
  • 1
    @HusseinBarada First one to convert string to numbers until `'.'` is encountered . It ends as any non-digit is encountered. Second loop is to covert characters after `'.'` to numbers . – ameyCU Oct 21 '15 at 12:06
  • 1
    @HusseinBarada `-12.83` first loop will convert first two characters (_after_ `'-'` in string) to integers and store in `val` , and second loop will do it for characters after `'.'` – ameyCU Oct 21 '15 at 12:07
  • 1
    @HusseinBarada This `if (s[i] == '.')++i;` is to get index of `'.'` and then increment `i` and use it in second loop . This `if` is to take action as `'.'` is encountered . – ameyCU Oct 21 '15 at 12:09
  • ok got it. The whole function makes more sense to me. Thanks for your help @ameyCU – Hussein Barada Oct 21 '15 at 12:38