gpt4 book ai didi

c - 将两位数字打印为字符

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

我有这行代码:

printf("%c\n", '65');

此代码将 5 打印到控制台。

我知道 65 不是有效字符且未分配给任何 ASCII 值,那么此输出背后的原因是什么?

最佳答案

单引号给出一个字符的ascii值,称为字符常量

printf("%c\n", '65');

是一个多字符常量,这是实现定义的

65'A' 字符的 ascii 值,所以我想你的意思是

printf("%c\n", 'A');

相当于

printf("%c\n", 65);

使用多字符字符常量,是实现定义的。例如 gcc

The compiler evaluates a multi-character character constant a character at a time, shifting the previous value left by the number of bits per target character, and then or-ing in the bit-pattern of the new character truncated to the width of a target character. The final bit-pattern is given type int, and is therefore signed, regardless of whether single characters are signed or not (a slight change from versions 3.1 and earlier of GCC). If there are more characters in the constant than would fit in the target int the compiler issues a warning, and the excess leading characters are ignored.

For example, 'ab' for a target with an 8-bit char would be interpreted as ‘(int) ((unsigned char) 'a' * 256 + (unsigned char) 'b')’, and '\234a' as ‘(int) ((unsigned char) '\234' * 256 + (unsigned char) 'a')’.

Reference

所以在 gcc 中你会得到 5 因为

printf("%c\n", '65');

等价

printf("%c\n", (int)(((unsigned char)'6' * 256) | (unsigned char)'5'));

最后从你的问题的标题来看,似乎你想要

printf("%d\n", 65);

即打印十进制值 65

关于c - 将两位数字打印为字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27982006/

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