gpt4 book ai didi

c - 为什么转换说明符 %o 和 %x 在 C 语言中对 printf() 和 scanf() 的作用不同?

转载 作者:太空宇宙 更新时间:2023-11-04 01:24:48 25 4
gpt4 key购买 nike

我正在从 Stephen Prata 的“C Primer Plus”一书中学习 C。在第 4 章中,作者指出在 printf() 中,%o 和 %x 分别表示 unsigned 八进制整数和 unsigned 十六进制整数,但在 scanf() 中,%o 和 %x 分别解释signed 八进制整数和signed 十六进制整数。为什么会这样?

我在VS 2015中写了如下程序来验证作者的说法:

#include <stdio.h>
int main(void)
#pragma warning(disable : 4996)
{
int a, b, c;

printf("Enter number: ");
scanf("%x %x", &a, &b);
c = a + b;
printf("Answer = %x\n", c);


while (getchar() != EOF)
getchar();
return 0;
}

代码证明了作者的主张。

如果输入有一对整数,其中正整数的绝对值大于负整数的绝对值,那么一切正常。

但是如果输入有一对整数,其中正整数的绝对值小于负整数的绝对值,那么输出就是您所期望的无符号 2的补码。

例如:

Enter number: -5 6
Answer = 1

Enter number: -6 5
Answer = ffffffff

最佳答案

C 标准规定对于类似 printf 的函数 (7.21.6.1 fprintf):

o,u,x,X
The unsigned int argument is converted to unsigned octal (o), unsigned decimal (u), or unsigned hexadecimal notation (x or X)

虽然对于类似 scanf 的函数,它说 (7.21.6.2 fscanf):

x
Matches an optionally signed hexadecimal integer, whose format is the same as expected for the subject sequence of the strtoul function with the value 16 for the base argument. The corresponding argument shall be a pointer to unsigned integer.

因此,作为一项额外功能,您可以写入一个负的十六进制数,scanf 会将其转换为系统格式(二进制补码)中相应的无符号数。

例如

unsigned int x;
scanf("%x", &x); // enter -1
printf("%x", x); // will print ffffffff

为什么他们觉得 scanf 需要这个稍微有用的功能,我不知道。可能是为了与其他转换说明符保持一致。

但是,这本书似乎错误地使用了该函数,因为标准明确规定您必须将指针传递给 unsigned int。如果将指针传递给带符号的 int,则正式调用未定义的行为。

关于c - 为什么转换说明符 %o 和 %x 在 C 语言中对 printf() 和 scanf() 的作用不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33216448/

25 4 0
文章推荐: python - pymssql 不返回结果数据
文章推荐: python - 使用 Python 的 Pandas 包将 hdf5 文件中的列从 int64 转换为日期时间
文章推荐: html - 如何使
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com