我的C程序的输出不是预期的

时间:2016-02-10 19:08:15

标签: c output character variable-assignment

#include<stdio.h>
#include<conio.h>
int main()
{
   char c, p;
   p=getchar();
   int n=p+259;
   c=n;
   putchar(c);
   return 0;
}

如果我输入'a'字符,有人可以告诉我为什么这个程序的输出是'd'字符?

如果p ='a',则n = 97 + 259 = 356。 如果我的n变量是356,如何为c赋值100('d'的ASCII码?)

2 个答案:

答案 0 :(得分:5)

char可以取0到255之间的值,因为它是8位。

97 + 259 = 356和356模256为100。

答案 1 :(得分:5)

char是8位数据类型,您大大超出了其最大代表性:

a -> ascii 97
97 + 259 -> 356
356 & 0xFF -> 100 - overflowed, strip off "high bit" which can't be stored.
100 -> ascii 'd'