gpt4 book ai didi

c - 为什么这个程序输出 Yes,而它应该抛出错误或 NO

转载 作者:行者123 更新时间:2023-11-30 18:48:29 26 4
gpt4 key购买 nike

这里 a + b 是 -14,它应该小于 'a',因此应该打印 NO,但它打印 yes。

unsigned int a = 6;
int b = -20;

if((a+b) > a){
printf("Yes");
} else {
printf("NO");
}

return 1;

最佳答案

根据C标准(6.3.1.8常用算术转换)

1 Many operators that expect operands of arithmetic type causeconversions and yield result types in a similar way. The purpose is todetermine a common real type for the operands and result. For thespecified operands, each operand is converted, without change of typedomain, to a type whose corresponding real type is the common realtype. Unless explicitly stated otherwise, the common real type is alsothe corresponding real type of the result, whose type domain is thetype domain of the operands if they are the same, and complexotherwise. This pattern is called the usual arithmetic conversions:

...

Otherwise, if the operand that has unsigned integer type has rankgreater or equal to the rank of the type of the other operand, thenthe operand with signed integer type is converted to the type of theoperand with unsigned integer type.

类型unsigned intint 具有相同的等级。

因此,示例中变量 b 的值被解释为无符号值。

如果在 printf 的函数调用中为表达式 ( a + b ) 使用正确的转换说明符 %u 那么您可能得到

#include <stdio.h>

int main(void)
{
unsigned int a = 6;
int b = -20;

printf( "a + b = %u\n", a + b );

return 0;
}


a + b = 4294967282

关于c - 为什么这个程序输出 Yes,而它应该抛出错误或 NO,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45684663/

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