我对输出感到困惑.所以我期望得到我的输出解释 [英] I'm confused with a output . So I'm expecting explaination For my output

查看:127
本文介绍了我对输出感到困惑.所以我期望得到我的输出解释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

输出为:-128 我应该添加输出镜头吗?

Output is : -128 should I add output shot

推荐答案

char是一个在大多数系统上都占用1个字节(8位)的a.您的实现似乎具有char表示带符号的类型,但是在其他实现上,它可以是无符号的.有符号类型的最大值是2 ^(n-1)-1,其中n是位数.因此 char 的最大值为2 ^(8-1)-1 = 2 ^ 7-1 = 128-1 = 127.最小值实际上是-2 ^(n-1).这意味着最小值是-128.当您添加超过最大值的东西时,它溢出并循环回到最小值.因此,如果您正在执行char算术,则为127 + 1 = -128.

char is a that, on most systems, takes 1 byte (8 bits). Your implementation seems to have char represent a signed type, however on other implementations it could be unsigned. The maximum value for a signed type is 2^(n-1)-1, where n is the number of bits. So the maximum value of char is 2^(8-1)-1=2^7-1=128-1=127. The minimum value is actually -2^(n-1). This means the minimun value is -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.

您永远不要使用char进行算术运算.使用signed charunsigned char代替.如果将char替换为unsigned char,程序将按预期打印128.请注意,仍然会发生溢出(无符号类型的范围为0到2 ^ n-1,因此,如果将1加到255,则unsigned char会溢出,给您0).

You never use char for arithmetic. Use signed char or unsigned char instead. If you replace your char with unsigned char the program would print 128 as expected. 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).

这篇关于我对输出感到困惑.所以我期望得到我的输出解释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆