gpt4 book ai didi

将无符号整数变量转换为有符号变量

转载 作者:行者123 更新时间:2023-12-02 03:21:48 25 4
gpt4 key购买 nike

为什么下面的程序输出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 章常规算术转换中的描述,如果您尝试在signedunsigned 之间执行算术运算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/

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