gpt4 book ai didi

c - K&R 练习 3-4 : Negative Numbers Represented In Binary

转载 作者:行者123 更新时间:2023-11-30 16:57:51 25 4
gpt4 key购买 nike

我很难理解这个练习:

In a two's complement number representation, our version of itoa does not handle the largest negative number, that is, the value of n equal to -(2^(wordsize-1)). Explain why not. Modify it to print that value correctly, regardless of the machine on which it runs.

这是 itoa 最初的样子:

void reverse(char s[], int n)
{
int toSwap;
int end = n-1;
int begin = 0;

while(begin <= end) // Swap the array in place starting from both ends.
{
toSwap = s[begin];
s[begin] = s[end];
s[end] = toSwap;

--end;
++begin;
}
}

// Converts an integer to a character string.
void itoa(int n, char s[])
{
int i, sign;
if ((sign = n) < 0)
n = -n;
i = 0;
do
{
s[i++] = n % 10 + '0';
} while ((n /= 10) > 0);

if (sign < 0)
s[i++] = '-';
s[i] = '\0';
reverse(s, i);
}

我找到了这个答案,但我不明白其中的解释: http://www.stevenscs.com/programs/KR/ $progs/KR-EX3-04.html

Because the absolute value of the largest negative number a word can hold is greater than that of the largest positive number, the statement early in iota that sets positive a negative number corrupts its value.

他们是说负数由于符号的原因比没有符号的正数包含更多的位吗?为什么乘以 -1 会影响大负数的存储方式?

最佳答案

在二进制补码表示中,可以表示的值范围是 -2<sup>n-1</sup>2<sup>n-1</sup>-1 。因此,使用 8 位,您可以表示 -128 到 127 范围内的值。这就是短语“一个字可以容纳的最大负数大于最大正数”的含义。

仅用 3 位进行说明以使其更清晰:

Value    Bits
----- ----
0 000
1 001
2 010
3 011
-4 100
-3 101
-2 110
-1 111

使用 3 位,我们无法表示 4二进制补码,所以 n = -n;不会给我们预期的结果1。这就是为什么原来的atoi上面的实现无法处理 INT_MIN .

<小时/>

  1. 有符号整数溢出的行为是未定义,这意味着没有固定的结果。

关于c - K&R 练习 3-4 : Negative Numbers Represented In Binary,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39258583/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com