本帖最后由 jackz007 于 2021-11-24 23:37 编辑 #include <stdio.h>
long long atoix(char s[])
{
long long c , e , i , k , r ;
for(i = 0 ; s[i] && s[i] != '-' && (s[i] < '0' || s[i] > '9') ; i ++) ;
k = (s[i] == '-') ? -1 : 1 ;
if(k == -1) i ++ ;
for(c = r = 0 ; s[i] ; i ++) {
if(s[i] >= '0' && s[i] <= '9') {
if(! c) e = k * (s[i] - '0') ;
else e = r * 10 + k * (s[i] - '0') ;
if((k > 0 && e > r) || (k < 0 && e < r)) {
r = e ;
c ++ ;
} else {
r = -1 ; // 溢出
break ;
}
} else if(c) break ;
}
return r ;
}
int main(void)
{
char s[256] ;
gets(s) ;
printf("%I64d\n" , atoix(s)) ;
}
编译、运行实况:D:\00.Excise\C>g++ -o x x.c
D:\00.Excise\C>x
9223372036854775807 <--- long long 正向最大值
9223372036854775807
D:\00.Excise\C>x
9223372036854775808 <--- 超出 long long 正向最大值
-1
D:\00.Excise\C>x
-9223372036854775808 <--- long long 负向最大值
-9223372036854775808
D:\00.Excise\C>x
-9223372036854775809 <--- 超出 long long 负向最大值
-1
D:\00.Excise\C>
|