我编写了这个程序来计算C中某些数据类型的最大值和最小值,有符号数据类型。问题是它给出了正确的最大值,但给出了不正确的最小值,尽管我认为我的逻辑是正确的。我知道有更好和有效的方法来获得结果,我也已经实施了这些方法。只需要知道给定代码出错的地方。
我做了什么?我已经使用 sizeof 运算符实现了这一点,然后计算类型中的位数并使用它来计算最大值和最小值。
提前感谢...
/*
* Program to calculate the size of various data types like :
* int, long, short, char
*
* Version 3
*
* Problem with this version : Working correct only for maximum value of a
* data type.
*
* Author : Ravi Malik
*/
#include<stdio.h>
int main()
{ int i, i_prev ;
long l, l_prev ;
char c, c_prev ;
short s, s_prev ;
for( i = 0, i_prev = -1 ; i > i_prev ; i = i << 1 | 0x01 )
i_prev = i ;
for( l = 0, l_prev = -1 ; l > l_prev ; l = l << 1 | 0x01 )
l_prev = l ;
for( c = 0, c_prev = -1 ; c > c_prev ; c = c << 1 | 0x01 )
c_prev = c ;
for( s = 0, s_prev = -1 ; s > s_prev ; s = s << 1 | 0x01 )
s_prev = s ;
printf("MAX_INT:%d and MIN_INT:%dn",i_prev,i);
printf("MAX_LONG:%ld and MIN_INT:%ldn",l_prev,l);
printf("MAX_CHAR:%d and MIN_CHAR:%dn",c_prev,c);
printf("MAX_SHORT:%hd and MIN_SHORT:%hdn",s_prev,s);
return 0;
}
-1 表示所有位都设置为 1。在 2 的补码中,最小值为 1 后跟零(仅适用于有符号数据类型)。
在你的例子中,你会得到 -1 在 i
、 l
、 c
或 s
中,因为它包含所有 1。
用 1 初始化它们,并保持仅左移 1(无按位 OR)。
for( i = 1, i_prev = -1 ; i > i_prev ; i = i << 1)
i_prev = i ;
MIN_INT = - (MAX_INT + 1)
可能是最简单的公式,一旦你正确地计算了MAX_INT
。
因此,对于 32 位有符号整数,MAX_INT
= +2,147,483,683,因此 MIN_INT
= - ( MAX_INT
+ 1) = -2,147,483,684。