gpt4 book ai didi

c - C 中的无符号 int 表现为负数

转载 作者:行者123 更新时间:2023-11-30 16:09:45 24 4
gpt4 key购买 nike

我不明白为什么以下代码的 unsigned int 输出为负。就像有符号的 int 一样。

  uint32_t yyy=1<<31;
printf("%d\n",yyy);

输出为:

-2147483648

这是-2^31

最佳答案

%d 的格式说明符需要一个 int,而不是 unsigned int,因此代码具有未定义的行为。来自 C99 标准部分 7.19.6.1 fprintf 函数:

If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined.

使用%u表示无符号整数:

uint32_t yyy=1u<<31;
printf("%u\n",yyy);

输出:

2147483648

关于c - C 中的无符号 int 表现为负数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59043752/

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