2

I tried to re-write the itoa() function from K&R exercises, but I failed to define it. I see the answer of the function in the library , but I can't understand what is inside the do block. Please explain it to me. Thanks!

 /* itoa:  convert n to characters in s */
 void itoa(int n, char s[])
 {
     int i, sign;

     if ((sign = n) < 0)  /* record sign */
         n = -n;          /* make n positive */
     i = 0;
     do {       /* generate digits in reverse order */
         s[i++] = n % 10 + '0';   /* get next digit */
     } while ((n /= 10) > 0);     /* delete it */
     if (sign < 0)
         s[i++] = '-';
     s[i] = '\0';
     reverse(s);
 }
4

2 回答 2

6

s[i++] = n % 10 + '0'; Means:

  1. s[i++] means char number i in char array s and increment i by 1
  2. n % 10 means that you take only the last digit, for example in 123, 123 % 10 returns 3 which is a digit, this is done to cut your number into digits so you can create a char with each of them.
  3. + '0' means that you add the ascii value of the char '0', for example the int 1 + '0' returns the character '1' so you can get a char array.
  4. n /= 10 means that we remove the last digit, indeed, we added it to our char array so we can remove it, for example 123 / 10 = 12 then you can do 12 % 10 to get the second digit: 2

This gives us a char array inverted, for example for 123 we got an array like {'3', '2', '1'} so at the end we call reverse s to (thx captain obvious) reverse our char array

For a negative n you can just add a '-' to your char array and multiply your n by -1 so it become positive and you can do your job as always :)

Hope it helps you :)

于 2018-07-05T11:38:28.483 回答
3

For a non-negative n:

n /= 10 removes the least significant digit from an integral type. It's shorthand for n = n / 10, and any remainder from n / 10 is discarded.

n % 10 extracts the least significant digit from n, and adding that to '0' gives you the textural equivalent of that number. (Note this idiomatic technique works for any character encoding supported by C.)

于 2018-07-05T11:31:45.683 回答