本帖最后由 jackz007 于 2021-10-21 03:39 编辑 #include <stdio.h>
bool notoverflow(int d , char c)
{
bool r = true ;
int max = 0x7fffffff , min = 0x80000000 ;
if((d > 0 && d * 10 + c < d) || (d < 0 && d * 10 - c > d)) r = false ;
return r ;
}
int main(void)
{
char c ;
int d , k ;
bool f ;
for(d = k = 0 , f = true ; (c = getchar()) != '\n' && f ;) {
if(c >= '0' && c <= '9') {
if(notoverflow(d , c - '0')) {
d = d * 10 + c - '0' ;
k ++ ;
} else {
f = false ;
}
} else {
if(k) break ;
}
}
if(k) {
if(f) printf("%d\n" , d) ;
else printf("数值溢出 !\n") ;
} else {
printf("没有输入任何数字.\n") ;
}
}
编译、运行实况D:\00.Excise\C>g++ -o x x.c
D:\00.Excise\C>x
ABCD
没有输入任何数字.
D:\00.Excise\C>x
12345678
12345678
D:\00.Excise\C>x
ABCDE12345678901234567890
数值溢出 !
D:\00.Excise\C>x
123456778
123456778
D:\00.Excise\C>x
2147483647
2147483647
D:\00.Excise\C>x
2147483648
数值溢出 !
D:\00.Excise\C>
|