zxhutu 发表于 2005-5-5 21:41

怎么判断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 &gt;= 48 &amp;&amp; *szTmp &lt;= 57){  
            nValue = *szTmp-48;   
            nResult = nResult*10+nValue;
        }
        else {
     return -1;
        }
        if( nResult &lt; 0 ) return -1;//out of range*****就是这里了!
        szTmp++;
    }
    return nResult;
}
</P>

ilikenba 发表于 2005-5-5 23:54

<P>int -2147483648~2147483647</P><P>这是32位编译器的int的取值范围,是否可以直接用来判断!</P>

ilikenba 发表于 2005-5-6 00:40

<P>  #include "math.h"
  int i ;
  int j ;
  j= 1&lt;&lt;(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&lt;&lt;(sizeof(int) + 1)-1;
  i=pow(2,j-1)-1;</P><P>  你可以在程序中用它来作越界判断的门槛!</P>

skiller 发表于 2005-5-6 16:28

恩,sizeof的确是个好的解决方式~!
页: [1]
查看完整版本: 怎么判断int型的变量超过取值范围