465 - Overflow

题目:465 - Overflow


题目大意: 高精度数的加法和乘法 ,判断输入的两个数和结果是超过int型的范围;

解题思路:用到atof 将字符串转换成浮点数;还有begin 高精度运算类模板;


#include<iostream>
#include<stdio.h>
#include<string.h>
#include <stdlib.h>
using namespace std;

const int N = 10000;

struct begin {

	int len;
	char s[N];
	begin() {
		
		len = 1;
		memset(s, 0 ,sizeof(s));
	}
	begin operator = (const char *s1);
	begin operator + (const begin &b);
	begin operator * (const begin & b);
	begin operator += (const begin & b);

};

begin begin::operator =(const char * s1) {

	len = strlen(s1);
	for (int i = 0; i < len ; i++) {

		s[i] = s1[len - 1 - i] - '0';
	}
	return * this ;
}

begin begin::operator +(const begin & b) {
	
	begin c;
	c.len = 0;
	int l = (len > b.len) ? len : b.len, i, a = 0;
	for (i = 0; i < l || a; i++) {
			
		a = a + s[i] + b.s[i];
		c.s[i] = a % 10;
		a = a / 10;
	}
	c.len = i;
	return c;
}

begin begin::operator +=(const begin& b) {

	*this = * this + b;
	return * this;
}

begin begin::operator *(const begin & b) {
	
	begin c;
	c.len = 0;
	begin sum;
	sum.len = 0;
	int i, j, k, a = 0;
	for (i = 0; i < b.len; i++) {

		for (k = i, j = 0; j < len || a; j++, k++) {
			
			a = a + s[j] * b.s[i]; 
			c.s[k] = a % 10 ;
			a = a / 10 ;
			
		}
		c.len = j + i;
		sum += c;
		memset(c.s, 0, sizeof(c.s));
	}
	
	return sum;
}


int main() {
		
		char s[3][N], ch;
		begin a, b, c;
		int i, j;
		double t = 2147483647 , d;

		while(scanf("%s%*c", & s[0]) != EOF && scanf("%c%*c", &ch) != EOF && scanf("%s%*c", & s[1]) != EOF) {
			
			a = s[0];
			b = s[1];
			if(ch == '+')
				c = a + b;
			else if(ch == '*') {
				
				int l1 = strlen(s[0]);
				int l2 = strlen(s[1]);
				if(l1 > l2) 
					
					c = a * b;
		
				else 
					c = b * a;
			}
			
			printf("%s %c %s\n", s[0], ch, s[1]);

			d = atof(s[0]);
			if(d > t)
				printf("first number too big\n");
			d = atof(s[1]);
			if(d > t)
				printf("second number too big\n");
			for( i = c.len - 1, j = 0; i >= 0; i--, j++)
				s[2][j] = c.s[i] + '0';
			s[2][j] = '\0';
		//	printf("%s\n",s[2]);
			d = atof(s[2]);
			if(d > t)
				printf("result too big\n");

			memset(a.s, 0, sizeof(a.s));
			memset(b.s, 0, sizeof(b.s));
			memset(c.s, 0, sizeof(c.s));
			memset(s[2], 0, sizeof(s[2]));

		}
	return 0;
}


你可能感兴趣的:(465 - Overflow)