最近在我的研究所,我得到了一个代码,并被要求找出答案。 代码看起来像这样。
#include <stdio.h> int main() { char ch=500; printf("%d\n",ch); }输出将为-12
我的问题是:我如何计算这种代码的值? 是否有任何寻找价值的公式或流程?
Recently in my Institute I was given a code and was asked to find out the answer. The code looks like this.
#include <stdio.h> int main() { char ch=500; printf("%d\n",ch); }The output will come as -12
My question is: How can I calculate the value for this kind of code? Is there any formula or process for finding the values?
最满意答案
代码在语法上是正确的,但没有按照你的想法做。 正如Paul Hankin建议你的编译器应该给你一个警告,因为你试图设置一个不适合char变量中的char的数字。
char是1个字节,因此如果有符号则可以存储最多127个数字,如果未签名则可以存储255个数字。 该值溢出,仅考虑低8位。
500 = 0b111110100
仅取低8位:0b11110100
MSB为1,因此它为负数。
1补码加1是0b00001100,即12
这就是你得到-12的原因。
用short或int替换它应该正确打印500。
The code is syntactically correct but not doing what you think. As Paul Hankin is suggesting your compiler should give you a warning as you are trying to set a number that does not fit into a char in a char variable.
A char is 1 byte so it can store a number up to 127 if signed or 255 if unsigned. The value overflows and only the lower 8 bits are taken into account.
500 = 0b111110100
Take only the lower 8 bits: 0b11110100
The MSB is 1 so it's negative number.
1-complement plus 1 is 0b00001100 which is 12
That's why you get -12.
Replacing it by a short or an int should correctly print 500.
更多推荐
发布评论