傻瓜问题求助
#include <stdio.h>#include <math.h>
int main()
{
int ch;
long long num = 0;
long long temp; // 临时变量,用于测试是否超出范围
int is_overflow = 0;
const int max_int = pow(2, sizeof(int) * 8) / 2 - 1;
const int min_int = pow(2, sizeof(int) * 8) / 2 * (-1);
printf("请输入待转换的字符串:");
do
{
ch = getchar();
if (ch >= '0' && ch <= '9')
{
temp = 10 * num + (ch - '0');
if (temp > max_int || temp < min_int)
{
is_overflow = 1;
break;
}
else
{
num = temp;
}
}
else
{
if (num)
{
break; // 如果已有数字,则退出循环
}
}
}
while (ch != '\n');
if (is_overflow)
{
printf("数值超出范围,结果未定义!\n");
}
else
{
if (!num)
{
printf("并未找到任何数值!\n");
}
else
{
printf("结果是:%d\n", num);
}
}
return 0;
}
if(ch>='0'&&ch<='9')
{
temp=10*num+(ch-'0');
if(temp>max_int||temp<min_int)
{
is_overflow=1;
break;
}
else
{
num=temp;
}
}这是老师的代码
这串代码没看懂求解if(ch>='0'&&ch<='9')
{
temp=10*num+(ch-'0');
if(temp>max_int||temp<min_int)
{
is_overflow=1;
break;
}
else
{
num=temp;
}
} 本帖最后由 jackz007 于 2022-10-12 19:41 编辑
哪串代码没看懂,关于 overflow?
看看什么才叫真正的溢出检测:
#include <stdio.h>
#define maxv 0x7fffffffffffffffLL
#define minv 0x8000000000000000LL
int overflow(long long d , char x)
{
long long mv ;
int r = 0 ;
if(d) {
mv = (d > 0) ? maxv : minv ;
if(mv / d >= 10) {
if(d > 0) {
if(mv - d * 10 < x) r = 1 ;
else r = 0 ;
} else {
if(mv - d * 10 > x) r = 1 ;
else r = 0 ;
}
} else {
r = 1 ;
}
}
return r ;
}
int main(void)
{
char ch ;
long long num ;
int c , s ;
printf("maxv = %I64d\n" , maxv) ;
printf("minv = %I64d\n" , minv) ;
for(num = c = 0 , s = 1 ; (ch = getchar()) != '\n' ;) {
if(ch >= '0' && ch <= '9') {
ch -= '0' ;
if(num < 0) ch = -ch ;
if(! overflow(num , ch)) {
num = num * 10 + ch ;
} else {
num = -1 ;
break ;
}
if(num && s < 0) num = -num ;
c ++ ;
} else {
if(s < 0) s = -s ;
if(! c) {
if(ch == '-') s = - s ;
} else {
break ;
}
}
}
printf("%I64d\n" , num) ;
}
编译、运行实况:
D:\\C>g++ -o x x.c
D:\\C>x
maxv = 9223372036854775807
minv = -9223372036854775808
9223372036854775807
9223372036854775807
D:\\C>x
maxv = 9223372036854775807
minv = -9223372036854775808
-9223372036854775808
-9223372036854775808
D:\\C>x
maxv = 9223372036854775807
minv = -9223372036854775808
9223372036854775808
-1
D:\\C>x
maxv = 9223372036854775807
minv = -9223372036854775808
-9223372036854775809
-1
D:\\C>
后两次打印 -1 就是因为溢出 ? if(ch>='0'&&ch<='9')
{
temp=10*num+(ch-'0');
if(temp>max_int||temp<min_int)
{
is_overflow=1;
break;
}
else
{
num=temp;
}
}
这串代码 大佬们 本帖最后由 jhq999 于 2022-10-13 08:19 编辑
if(ch>='0'&&ch<='9')
{
temp=10*num+(ch-'0');//例如一个字符串“2341567825566”,num=0,temp=10*0+'2'-'0'=2,num=2,下一个temp=2*10+'3'-'0'=23以此类推,
//直到234,156,782时,
if(temp>max_int||temp<min_int)//再进一步‘5’时,就大于2,147,483,647(2^31-1)超出int类型正数范围,判断为溢出,负数判断temp<min_int也如此?
{
is_overflow=1;
break;
}
else
{
num=temp;
}
}
先领个币 楼上说的很清楚了 {:10_254:}
页:
[1]