# 《C程序设计语言》练习 3-4

n 等于-2 字长-1的情况。请解释其原因。修改该函数，使它在任何机器上运行时都能打印出正确

/* 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);
} 

n的初始值为-128 。


void itoa2(int n, char s[])
{
int sign, i;
sign = n;
i = 0;
do {
if (sign < 0)
s[i++] = -(n % 10) + '0';
else
s[i++] = n % 10 + '0';

} while ((n /= 10) != 0);
if (sign < 0)
s[i++] = '-';
s[i] = '\0';
reverse(s);
}

/*练习 3-4 在数的对二的补码表示中，我们编写的 itoa 函数不能处理最大的负数，即
n 等于-2 字长-1的情况。请解释其原因。修改该函数，使它在任何机器上运行时都能打印出正确

*/

#include <stdio.h>

/*原函数*/
void itoa(int n, char s[]);
void itoa2(int n, char s[]);
void reverse(char s[]);
main()
{
int n;
n = (~0U >> 1) + 1; //int 最小值
char s[1024];
itoa(n, s);
printf("%s\n", s);
itoa2(n, s);
printf("%s\n", s);
}

void itoa2(int n, char s[])
{
int sign, i;
sign = n;
i = 0;
do {
if (sign < 0)
s[i++] = -(n % 10) + '0';
else
s[i++] = n % 10 + '0';

} while ((n /= 10) != 0);
if (sign < 0)
s[i++] = '-';
s[i] = '\0';
reverse(s);
}
/* 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);
}

void reverse(char s[])
{
int i, j, c;
for (j = 0; s[j] != '\0'; j++)
;
for (i = 0, j--; i < j; i++, j--)
{
c = s[i];
s[i] = s[j];
s[j] = c;
}
}

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客