这是我的代码:
#include <stdio.h>
void main() {
char a, b;
char c;
printf("enter 2 chars: ");
a = getchar();
b = getchar();
c = a - b;
printf("%d",c );
}
我正在尝试查找两个字符之间的绝对值,例如 'A'&'a'=>32 'a'&'A'=>32 我的代码显示否定答案,如果不使用abs函数我应该做什么,或者如果我尝试了这个:
printf("%u",c );
但它给了我 4294967264。有没有任何简单的方法来做到这一点?它应该使用 getchar 和 putchar!
最佳答案
没有分支:(假设二进制补码整数表示)
#include <stdio.h>
int main(void)
{
printf("Enter 2 chars: ");
char a = getchar();
char b = getchar();
char c = a - b;
c = (c^-(c < 0)) + (c < 0);
printf("%d\n", c);
}
分成几部分:
(c < 0)
给出0
当c
为正:
c = (c^-0) + 0
〜> c = c^0
... $foo XOR 0 给出 $foo
c = c
无事可做。
(c < 0)
给出1
当c
为负:
c = (c^-1) + 1
... -1
二进制补码中的所有位均已设置 ( ~0
)
c = (c^(~0)) + 1
...负c
二进制补码 XOR ~0
给出-c - 1
c = -c - 1 + 1
〜> c = -c
gcc 8.3 -O3:(cl v15.9.0-pre.3.0 生成等效的程序集)
mov edx, edi ; edx = c
shr edx, 31 ; right shift, keep only the sign bit (c < 0) [sign]
mov eax, edx ; eax = [sign]
neg eax ; eax = -[sign]
xor eax, edi ; eax = -[sign] xor c
add eax, edx ; eax += [sign]
关于c - ASCII 表中不带 "abs"或 "if"的 2 个字符之间的差的绝对值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53470297/