英文:
What happens when operator is >,+ and two operands are unsigned int, char
问题
#include <stdio.h>
int main(void) {
unsigned int n = 10;
char m = -1;
if (m < n)
printf("m < n\n");
else
printf("m > n\n");
printf("m + n = %u\n", m + n);
return 0;
}
在我在Windows上的MinGW64中运行这段代码时,它会打印出"m > n"和"m + n = 9"。我不明白为什么会出现"m + n = 9"和"m > n"。
英文:
#include <stdio.h>
int main(void) {
unsigned int n = 10;
char m = -1;
if (m < n)
printf("m < n\n");
else
printf("m > n\n");
printf("m + n = %u\n", m + n);
return 0;
}
When I run this code in MinGW64 on windows. It prints "m > n","m + n = 9"
I can't understand why "m + n = 9" and "m > n".
答案1
得分: 2
我不明白为什么 "m + n = 9" 和 "m > n"。
只能比较兼容的整数,所以char
被转换为unsigned int
,其值是(假设32位整数和二进制补码负整数)0xffffffff
,远远大于10
。
当你添加char
时,它被转换为unsigned int
并相加。这种转换后的负数的二进制补码相加会给出正确的值(它的行为类似于减法)。更多信息:https://en.wikipedia.org/wiki/Two%27s_complement
英文:
> I can't understand why "m + n = 9" and "m > n".
You can only compare compatible integers so char
is being converted to unsigned int
and its value is (assuming 32 bits integers and two complement negative integers) 0xffffffff
which is much more than 10
.
When you add char is converted to unsigned int and added. Two complements addition of such converted negative number gives the correct value (it acts like substraction). More information: https://en.wikipedia.org/wiki/Two%27s_complement
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论