我从《let us c pg no.26》一书中创建了一个简单的程序,这是一个示例来说明,代码有点像这样
#include <stdio.h>
int main() {
char x,y;
int z;
x = 'a';
y = 'b';
z = x + y;
printf("%d", z);
return 0;
}
但是我期望的输出是字符串 ab (我知道 z 是 int,但这仍然是我能想到的输出),但输出却是 195,这让我感到震惊,所以请帮助我简单地解决这个问题话。
最佳答案
根据某些协议(protocol)(例如 Ascii 或 Unicode),字符/字母在内部表示为数字。 ASCII 是表示最常见符号和字母的流行标准。这是 ASCII 表。该表列出了 ASCII 中的所有常见符号/字母本质上是 0 到 255 之间的数字(ASCII 有两部分:0 到 127 是标准 ASCII;上限范围 128 到 255 在扩展 ASCII 中定义;使用了扩展 ASCII 的许多变体)。
将其放入代码上下文中,发生的情况如下。
// The letter/char 'a' is internally saved as 97 in the memory
// The letter/char 'b' is internally saved as 98 in the memory
x = 'a'; // this will copy 97 to x
y = 'b'; // this will copy 98 to x
z = x +y ; // 97+98=195 -> z
如果要打印“ab”,则必须有两个相邻的字符。这是你应该做的
char z[3];
z[0]='a'; //move 'a' or 97 to the first element of z (recall in C, the index is zero-based
z[1]='b';//move 'b' or 98 to the second element or z
z[2]=0; //In C, a string is null-ended. That is, the last element must be a null (i.e.,0).
print("%s\n",z); // you will get "ab"
或者,您可以根据 Ascii 表通过以下方式获取“ab”:
char z[3];
z[0]=97; //move 97 to the first element of z, which is 'a' based on the ascii table
z[1]=98;//move 98 to the second element or z, which is 'b'
z[2]=0; //In C, a string is null-ended. That is, the last element must be a null (i.e.,0).
print("%s\n",z); // you will get "ab"
编辑/评论:
考虑此评论:
"Chars are signed on x86, so the range is -128 ... 127 and not 0 ... 255 as you state ".
请注意,我没有提到 C 中的 char 类型的范围是 0 ... 255。我仅在 ASCII 标准的上下文中引用 [0 ... 255 ]。
关于c - int 数据类型的意外输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57541585/