gpt4 book ai didi

c - scanf %u 负数?

转载 作者:太空狗 更新时间:2023-10-29 15:05:25 27 4
gpt4 key购买 nike

我试过 scanf("%u",&number) 并且我输入了负数问题是当我 printf("%d",number) 我得到负数。我认为这会阻止我读取负数。scanf("%d",&number)scanf("%u",&number) 真的是一回事吗?还是只是为了便于阅读。

我是不是在做一些所谓的未定义行为?

编辑:

来自 Wikipedia我读了这个:

%u : Scan for decimal unsigned int (Note that in the C99 standard theinput value minus sign is optional, so if a minus sign is read, noerrors will arise and the result will be the two's complement of anegative number, likely a very large value.

阅读 SO 答案及以上内容有点令人困惑。有人可以说得更清楚吗?

最佳答案

是的,无论哪种方式,这都是未定义的行为。

考虑到变量 numberunsigned 类型,printf() 中的 %d 需要参数 signed int类型,传一个unsigned类型就是UB。

OTOH,如果number是有符号类型,使用%u扫描首先是UB。

如你所料

[...] prevent me from reading negative number

格式说明符用于防止不正确的输入。如果格式说明符与提供的参数不匹配,它会调用 undefined behavior .

引用C11,附件J.2,场景调用UB,

The result of a conversion by one of the formatted input functions cannot be represented in the corresponding object, or the receiving object does not have an appropriate type

关于c - scanf %u 负数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38684386/

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