为什么下面的程序输出b 大于a? 即使 b 包含 -2。
void main()
{
unsigned int a=12;
int b=-2;
if(a>b)
printf("a is greater");
else
printf("b is greater");
getch();
}
最佳答案
首先引用关系运算符的C11
标准,第6.5.8章
If both of the operands have arithmetic type, the usual arithmetic conversions are performed.
现在,按照第 6.3.1.8 章常规算术转换中的描述,如果您尝试在signed
和unsigned
之间执行算术运算code> 整数(类型),signed
将被提升为 unsigned
类型(更高级别),然后操作将发生。
所以,在这里,为了进行比较,b
的值被转换为 unsigned
类型,您得到的是错误输出那里。
引用同一章节的相关部分
[...] Otherwise, both operands are converted to the unsigned integer type corresponding to the type of the operand with signed integer type.
您还可以查看通常的算术提升规则 here
也就是说,void main()
应该是 int main(int argc, char* argv[])
,或者至少是 int main(无效)
。
关于将无符号整数变量转换为有符号变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32867000/