UVA-465 Overflow

UVA-465 Overflow

题目大意:判断第一个因子,第二个因子和结果有没有溢出,运算包括加法乘法

Sample Input

300 + 3
9999999999999999999999 + 11

Sample Output

300 + 3
9999999999999999999999 + 11
first number too big
result too big

解题思路:伪高精度,直接拿去和 int 的最大取值比较即可。

//UVA-465 Overflow
#include <iostream>
#include <cstdio>
#include <climits>
#include <cstdlib>
using namespace std;

const int inf = INT_MAX;   //INT_MAX头文件 climits

int main() {
    double a, b;
    char s1[1010],s2,s3[1010];
    while (scanf("%s %c %s",s1,&s2,s3) != EOF) {
        printf("%s %c %s\n",s1,s2,s3);
        a = atof(s1);      //字符串转换为双精度浮点数(double),头文件 cstdlib
        b = atof(s3);
        if (s2 == '+') {
            if (a > inf)
                printf("first number too big\n");
            if (b > inf)
                printf("second number too big\n");
            if (a + b > inf)
                printf("result too big\n");
        }
        if (s2 == '*') {
            if (a > inf)
                printf("first number too big\n");
            if (b > inf)
                printf("second number too big\n");
            if (a * b > inf)
                printf("result too big\n");
        }
    }
    return 0;
}
参考了此处 的博客,里面有写关于为什么不直接用 double 型,如果数字太大的话,字符数组存储转化为 double 后应该后面的还会变为 0 ,超过了 double 型最大值。但此时仍比 int 最大值大,但输出的时候需要输出准确值,所以还要用 double 。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值