您的位置:首页 > 其它

UVA-465 Overflow

2016-07-19 21:00 363 查看

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 。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: