gpt4 book ai didi

c - 在 if 语句中使用 scanf

转载 作者:行者123 更新时间:2023-11-30 18:39:10 25 4
gpt4 key购买 nike

为什么输出是“4”? ,当输入为“A”时

int main() {  int a = 5;  
if(scanf("%d",&a))
printf("%d",a+1);
else
printf("%d",a-1);
}

最佳答案

当使用类型分隔符 %d 时,函数期望输入有效的有符号十进制整数。很明显,符号'A'不是数字,因此输入失败。

现在出现一个问题:在这种情况下函数将返回什么?

根据函数scanf的描述(C标准,7.21.6.4 Scanf函数):

3 The scanf function returns the value of the macro EOF if an input failure occurs before the first conversion (if any) has completed. Otherwise, the scanf function returns the number of input items assigned, which can be fewer than provided for, or even zero, in the event of an early matching failure.

所以if语句中的条件

if(scanf("%d",&a))  

计算结果为 0(假),并且执行了 else 语句。

else  
printf("%d",a-1);

输出 4。

请注意,通常您可以输入整数符号'A'。但在这种情况下,相应的整型变量必须声明为 unsigned,并且 scanf 的格式说明符必须为 %x

例如

#include <stdio.h>

int main( void )
{
unsigned int a = 5;

if ( scanf( "%x", &a ) )
{
printf( "%u\n", a + 1 );
}
else
{
printf( "%u\n", a - 1 );
}
}

在这种情况下,输出将为 11。:) scanf 会将符号 'A' 视为 10 的十六进制表示形式。

关于c - 在 if 语句中使用 scanf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30762284/

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