uva 465 - Overflow

题目地址:http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=97&page=show_problem&problem=406

 

用java的大数类处理,提交WA,未找到原因,好蛋疼。。。

import java.math.BigInteger;
import java.util.Scanner;

public class Main {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner cin = new Scanner(System.in);
		Integer maxInt = Integer.MAX_VALUE;
		BigInteger a = null;
		BigInteger b = null;
		BigInteger res = null;
		String op = null;
		BigInteger max = new BigInteger(maxInt.toString());

		while (cin.hasNext()) {
			a = new BigInteger(cin.next());
			op = cin.next();
			b = new BigInteger(cin.next());

			System.out.println(a + " " + op + " " + b);

			if (a.compareTo(max) > 0)
				System.out.println("first number too big");

			if (b.compareTo(max) > 0)
				System.out.println("second number too big");

			if (op.equals("+") && ((a.add(b)).compareTo(max) > 0))
				System.out.println("result too big");
			if (op.equals("*") && ((a.multiply(b)).compareTo(max) > 0))
				System.out.println("result too big");

		}

	}
}

 

C++代码AC了,偷了个懒没有用字符串处理,而是用double存储,double有15-16位精度,对于最大不超过10位的int够用了,即使整数数字很大,超过了double的精度表示范围,但是数字的数量级也足以溢出了。

#include<cstdio>
#include<cstdlib>
#include<cstring>


const int MAX=1000;

int main()
{
	char a[MAX];
	char b[MAX];
	
	char op;
	const int maxInt=0x7fffffff;
	double aNum;
	double bNum;



	while(scanf("%s %c %s",a,&op,b)!=EOF)
	{
		printf("%s %c %s\n",a,op,b);
		
		
		aNum=atof(a);
		bNum=atof(b);
		
		if(aNum>maxInt)
			printf("first number too big\n");

		if(bNum>maxInt)
			printf("second number too big\n");

		if(op=='+')
		{
			if(aNum+bNum > maxInt)
				printf("result too big\n");			
		}
		else
		{
			if(aNum*bNum>maxInt)
				printf("result too big\n");
			
		}
		
	}


	return 0;
}

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值