gpt4 book ai didi

c - 扫描数据多于预定义值的数字

转载 作者:太空宇宙 更新时间:2023-11-03 23:23:39 24 4
gpt4 key购买 nike

#include<stdio.h>
main()
{

unsigned int num;
printf("enter the number:\n");
scanf("%u",&num);//4294967299 if i'm scanning more than 4G its not scanning
printf("after scanning num=%u\n",num);// 4294967295 why its giving same 4G

/* unsigned char ch;
printf("enter the character:\n");
scanf("%d",&ch);// if i/p=257 so its follow circulation
printf("after scanning ch=%d\n",ch);// 1 its okk why not in int ..
*/
}

为什么通过scanf()扫描输入时循环不跟随,为什么在char的情况下循环?

最佳答案

C11 标准草案 n1570 7.21.6.2 说如下

paragraph 10

[...] the input item [...] is converted to a type appropriate to the conversion specifier. If the input item is not a matching sequence, the execution of the directive fails: this condition is a matching failure. Unless assignment suppression was indicated by a *, the result of the conversion is placed in the object pointed to by the first argument following the format argument that has not already received a conversion result. If this object does not have an appropriate type, or if the result of the conversion cannot be represented in the object, the behavior is undefined.

现在,这里的“转换”一词用于字符串=>结果数据类型转换,不能理解为整数转换。由于转换为十进制整数的字符串 "4294967299" 无法在 32 位宽的 unsigned int 类型的对象中表示,因此标准的解读表明行为未定义,即

behavior, upon use of a nonportable or erroneous program construct or of erroneous data, for which this International Standard imposes no requirements

因此,您的问题的答案是 C 标准没有说明这种情况下的行为,您看到的行为是您的编译器和 C 库实现所展示的行为,并且不可移植;在其他平台上,可能的行为可能包括:

ignoring the situation completely with unpredictable results, to behaving during translation or program execution in a documented manner characteristic of the environment (with or without the issuance of a diagnostic message), to terminating a translation or execution (with the issuance of a diagnostic message).

关于c - 扫描数据多于预定义值的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32648358/

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