首页 > 解决方案 > 将2个字符加在一起时出现问题

问题描述

   char c = '2';
   char d = '3';
   char e = 'c' + 'd';
   int digit = e - '0'; // ACSII into int
   printf("digit = %d \n", digit); //should display 23
   printf("char c : %c \n",c); //should display 2
   printf("char d : %c \n",d); //should display 3

我要做的是在不使用 strcat() 函数将 23 显示为 int 的情况下进行字符串连接。
但是我似乎得到了:

数字 = - 105

标签: c

解决方案


溢出!Achar只有8位长。默认情况下,它是有符号的,所以范围是-128 <= x < 128. 您正在添加字符'c'and 'd'(不是变量cand d),这意味着您实际上是在添加 ASCII 值,因此evalue也是如此199。因为是签名的,所以真的199 - 256 == -57。然后减去ASCII 码'0'48得到-57 - 48 = -105.


推荐阅读