怎么判断int型的变量超过取值范围
<P>我写了一个这样的函数,想把字符串转化为int型的,代码如下,</P><P>其中的int超出了取值范围的判断好像不太合理,请各位指教!</P>
<P>int StringToInt(const char* szStr){
int nResult = 0;
//int nValue = 0;
const char* szTmp = szStr;
while (*szTmp){
if(*szTmp >= 48 && *szTmp <= 57){
nValue = *szTmp-48;
nResult = nResult*10+nValue;
}
else {
return -1;
}
if( nResult < 0 ) return -1;//out of range*****就是这里了!
szTmp++;
}
return nResult;
}
</P> <P>int -2147483648~2147483647</P><P>这是32位编译器的int的取值范围,是否可以直接用来判断!</P> <P> #include "math.h"
int i ;
int j ;
j= 1<<(sizeof(int) + 1);
i=pow(2,j-1)-1;</P><P>上面的i就是32位编译器要用来作判断的值!下面是16位编译器的值!</P><P> #include "math.h"
int i ;
int j ;
j= 1<<(sizeof(int) + 1)-1;
i=pow(2,j-1)-1;</P><P> 你可以在程序中用它来作越界判断的门槛!</P> 恩,sizeof的确是个好的解决方式~!
页:
[1]