我已經編寫了此程序來計算C,有符號數據類型中某些數據類型的最大值和最小值。問題是它給出了正確的最大值,但不正確的最小值,儘管我認爲我的邏輯是正確的。我知道有更好的和有效的方法來獲得結果,我也已經實施了。只需要知道給定代碼出錯的地方。用於計算數據類型範圍的C程序
我做了什麼? 我已經實現了這個使用sizeof運算符,然後計算類型中的位數,並使用它來計算最大值和最小值。
Thanx提前.......
/*
* 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:%d\n",i_prev,i);
printf("MAX_LONG:%ld and MIN_INT:%ld\n",l_prev,l);
printf("MAX_CHAR:%d and MIN_CHAR:%d\n",c_prev,c);
printf("MAX_SHORT:%hd and MIN_SHORT:%hd\n",s_prev,s);
return 0;
}
以防萬一你不知道:最有效的方法是使用'limits.h'中的常量。 – user694733