繁体   English   中英

int 数据类型的意外输出

[英]Unexpected output of int datatype

我从书中创建了一个简单的程序让我们 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,这让我感到震惊,所以请帮助我用简单的语言弄清楚这一点。

根据某些协议(例如,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"

编辑/评论:

考虑到这个评论:

“字符在 x86 上签名,因此范围是 -128 ... 127 而不是 0 ... 255,如您所说”。

请注意,我没有提到 C 中的 char 类型的范围是 0 ... 255。我仅在 ASCII 标准的上下文中提到 [0 ... 255 ]。

你总结了 97 到 98,因此是 195。

int中输入两个char的总和会将这些char提升为int然后存储结果。

然后,如果您希望将其打印为字符串,则可以printf("%s\\n", z); . 打印%d会将变量解释为十进制有符号整数。

不要将其打印为字符串,因为您不知道第一个 chars 数组终止符有多远。

C 中的字符数组,对于许多函数,例如printf ,不会在其大小结束的地方结束,而是在终止符字符( 0x000'\\0' )标记其结束的地方结束。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM