我正在尝试运用K&R的2.1.练习内容如下:
写一个程序,以确定的范围
char,short,int,和long变量,都signed和unsigned通过打印从标准头合适的值,并通过直接计算.如果计算它们会更难:确定各种浮点类型的范围.
打印标准标题中常量的值很简单,就像这样(例如只显示整数):
printf("Integral Ranges (from constants)\n");
printf("int max: %d\n", INT_MAX);
printf("int min: %d\n", INT_MIN);
printf("unsigned int max: %u\n", UINT_MAX);
Run Code Online (Sandbox Code Playgroud)
但是,我想以编程方式确定限制.
我尝试了这个代码似乎应该可以工作,但它实际上进入一个无限循环并被卡在那里:
printf("Integral Ranges (determined programmatically)\n");
int i_max = 0;
while ((i_max + 1) > i_max) {
++i_max;
}
printf("int max: %d\n", i_max);
Run Code Online (Sandbox Code Playgroud)
为什么这会陷入循环?似乎当整数溢出时,它会从2147483647跳转到-2147483648.递增的值显然小于先前的值,因此循环应该结束,但它不会.
最近我对这个问题很困惑.也许是因为我没有阅读语言规范(这是我的错,我知道).
C99标准没有说明编译器应该使用哪个负数表示.我一直认为存储负数的唯一正确方法是两个补码(在大多数情况下).
所以这是我的问题:您是否知道任何现在的编译器默认实现一个补码或符号幅度表示?我们可以用一些编译器标志更改默认表示吗?
确定使用哪种表示的最简单方法是什么?
那么C++标准呢?
使用二进制补码在内存中存储负值的好处是众所周知的,并在本板中进行了充分讨论.
因此,我想知道:
是否存在一些架构,它们选择了一种不同的方式来表示内存中的负值,而不是使用两个补码?如果是这样的话:原因是什么?
请查看以下代码并帮助我理解它
int a=1;
int b=~1;
printf("%d",b);
Run Code Online (Sandbox Code Playgroud)
输出是:
-2
Run Code Online (Sandbox Code Playgroud)
所以这表示 1=(00000001) 当经历 ~ 时产生 (11111110),它是数字 2 的 2 补码,因此 -2 就是答案。那么 100 总是被假定为 -4 而不是 4 ?
我注意到在windows和linux x86上,float是4bytes,double是8,但long xins分别是x86和x86_64上的12和16.C99应该用特定的整体尺寸打破这种障碍.
最初的技术限制似乎是由于x86处理器无法处理超过80位的浮点运算(加上2个字节来进行舍入),但为什么标准与int类型相比不一致?他们为什么不至少达到80bit标准化?
根据标准,operator <<为负签名的第一个操作数产生一个未定义的行为.
C++ 11 5.8.2
The value of E1 << E2 is E1 left-shifted E2 bit positions; vacated bits are zero-
filled. If E1 has an unsigned type, the value of the result is E1 × 2 pow E2,
reduced modulo one more than the maximum value representable in the result type.
Otherwise, if E1 has a signed type and non-negative value, and E1 × 2 pow E2 is
representable in the result type, then that is the resulting value; …Run Code Online (Sandbox Code Playgroud) 我试图检查收到的消息号是否在给定范围内.每次消息号增加时.如果我期待数字10,我接受任何号码为10+的消息.所以序列号为10到15.我使用的是unsigned int.因此,当预期数量为65532时,我可以接受65532 + 10(所以min = 65532和max = 5).如何检查我收到的号码是否在此范围内?
我刚刚开始学习 C,一个问题困扰了我一段时间。如果我写
int i = -1;
unsigned int j = 2;
unsigned int k = -2;
Run Code Online (Sandbox Code Playgroud)
整数文字-1and 2and的类型是什么-2,它如何转换为存储在signed intand 中unsigned int?
有符号整数是什么意思,是变量还是整数文字的属性?比如-2有符号整数和2无符号整数?
我查找的所有内容只是告诉我如何在 C 中进行补充运算/计算。
我想知道 C 在内部使用什么表示以及它如何处理溢出。