简体   繁体   English

我对输出感到困惑。 所以我期待对我的输出的解释

[英]I'm confused with a output . So I'm expecting explaination For my output

  #include <stdio.h>
    {
        char num = 127;
        num = num + 1;
        printf("%d", num);
      return 0;
     }

Output is : -128输出为:-128

Edit : I was a newbie at the time I posted this question.编辑:我在发布这个问题时还是个新手。 Lol :).哈哈 :)。

char is a that, on most systems, takes 1 byte (8 bits). char是一个,在大多数系统上,需要 1 个字节(8 位)。 Your implementation seems to have char represent a signed type, however on other implementations it could be unsigned.您的实现似乎有char表示有符号类型,但是在其他实现中它可能是无符号的。 The maximum value for a signed type is 2^(n-1)-1, where n is the number of bits.有符号类型的最大值是 2^(n-1)-1,其中 n 是位数。 So the maximum value of char is 2^(8-1)-1=2^7-1=128-1=127.所以char的最大值为2^(8-1)-1=2^7-1=128-1=127。 The minimum value is actually -2^(n-1).最小值实际上是-2^(n-1)。 This means the minimun value is -128.这意味着最小值为 -128。 When you add something that goes over the maximum value, it overflows and loops back to the minimum value.当您添加超过最大值的内容时,它会溢出并循环回最小值。 Hence, 127+1=-128 if you are doing char arithmetic.因此,127+1=-128 如果你在做char算术。

You never use char for arithmetic.你从不使用char进行算术运算。 Use signed char or unsigned char instead.请改用有signed charunsigned char If you replace your char with unsigned char the program would print 128 as expected.如果你用unsigned char替换你的char程序将按预期打印 128 。 Just note that the overflow can still happen (unsigned types have a range from 0 to 2^n-1, so unsigned char overflows if you add 1 to 255, giving you 0).请注意,溢出仍然可能发生(无符号类型的范围从 0 到 2^n-1,因此如果将 1 加到 255,则无unsigned char溢出,结果为 0)。

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

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