c - 值字符如何转换为整数?

标签 c

下面是程序的源代码,如果输入是97,则输出为

Please enter a number between 97 and 121:97

The 1st output is: a
The 2nd output is: a
The 3rd output is b
The 4th output is 97
--------------------------------

这个输出背后的逻辑是什么?整数如何转换为字符?是ASCII Chart

#include <stdio.h>
#include <conio.h>
int main () 
{
    int a;
    printf("\n%s enter a number between 97 and 121:" , "Please");
    scanf("%d", &a);
    printf("\nThe 1st outpit is: %c", a);
    printf("\nThe 2nd output is: %c" ,a++);
    printf("\nThe 3rd output is %c", a--);
    printf("\nThe 4th output is %d", a);
    return 0;
}

最佳答案

How is an integer converted into character?

让我们先看看“%d”

printf("\nThe 4th output is %d", a);
此时

a 的值为 97。当 printf() 看到一个 "%d" 时,它期望看到一个 int 作为下一个参数 - 确实如此 - 很好。 97 会导致打印 2 个字符:'9''7'

fprintf c
The int argument is converted to signed decimal in the style [−]dddd..
C11dr §7.21.6.1 8

<小时/>

现在“%c”

printf("\nThe 1st outpit is: %c", a);
此时

a 的值为 97。当 printf() 看到 "%c" 时,它期望看到 int 作为下一个参数 - 这很好 - 很好。然后将int值转换为unsigned char,仍然是值97。然后“打印”97对应的字符。不过,这种对应关系是压倒性的ASCII对于值 0-127,因此会看到字符“a”。

..., the int argument is converted to an unsigned char, and the resulting character is written.

关于c - 值字符如何转换为整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52168025/

相关文章:

c - 如何在 Windows 或 Linux 中查找 C 函数的运行时间

c - 使用 winapi 在 C 语言中为 shell 实现管道

c++ - 构建失败 Netbeans 7.4 C/C++

C 程序在尝试引用结构数组时崩溃

c - 中断处理程序是否有超时?

C - DLL 需要 __stdcall 并导入 __cdecl lib

c - 为什么在 glib 主上下文中用 zmq_poll() 替换 poll() 时出现段错误?

c - BMI分类结构

c++ - 使用 Ninja 构建系统,我可以清理中间构建产品吗?

c - 嵌套循环分析(每个循环限制内循环)