在 C 编程中,字符变量保存 ASCII 值(0 到 127 之间的整数)而不是字符本身。这个整数值是字符的ASCII码。
例如
'A'
的ASCII值为65、
这意味着,如果将
'A'
分配给字符变量,则 65 将存储在变量中,而不是
'A'
本身。
现在,让我们看看如何在 C 编程中打印字符的 ASCII 值。
打印 ASCII 值的程序
#include <stdio.h> int main() { char c; printf("Enter a character: "); scanf("%c", &c); // %d displays the integer value of a character // %c displays the actual character printf("ASCII value of %c = %d", c, c); return 0; }
输出
Enter a character: G ASCII value of G = 71
在这个程序中,要求用户输入一个字符。字符存储在变量
c 中。
当使用
%d
格式字符串时,显示71(
G
的ASCII值)。
当使用
%c
格式字符串时,显示
'G'
本身。