ITeye博客

C++之大整数相加

Qaohao · 2009-09-17 17:38 · C\C++ · 编程语言 · Markdown

好久没有用过c++写代码了,自从工作一直都用的是java,今天有空就写了端代码,放在自己博客里面晒晒。 自己用c++封装了一个bigDecimal类,里面实现了大整数相加的操作,目前不支持负数相加。 代码如下:


/**************************************************************************************************************
 * Class    : bigDecimal
 * Function : It mainly processes math logical for bigDecimal, such as add, minus, mutiply, divide and ect.
 *            There only presents add operation for bigDecimal ,other to do in future.
 * Author   : qaohao
 * Version  : 1.0
 * Date     : Sep 17th, 2009.
 *
 **************************************************************************************************************/

#include<iostream>

// assign buffer size for console input.
const int IN_STREAM_BUFFER_SIZE = 1000;

const int OK= 0;
const int ERR_CODE_NULL= 1;
const int ERR_CODE_NOTHING =2;
const int ERR_CODE_UNSUPPORT_NUM =3;


/**************************************************************************************************************
 *   Class define part
 **************************************************************************************************************/
class bigDecimal
{
public:
	bigDecimal(void);
	bigDecimal(const char* decimal);
	~bigDecimal(void);
	bigDecimal& operator+(const bigDecimal& rDecimal);
	friend std::ostream& operator<<(std::ostream& os, const bigDecimal& decimal);
	friend std::istream& operator>>(std::istream& is, bigDecimal& decimal);
private:
	int bits;
	char* contents;
	int validate(const char* input);
	void throwExp(int errCode);
};


/**************************************************************************************************************
 *   Class Implementation part
 **************************************************************************************************************/

/*
 * create an bigDecimal with its content is 0.
 */
bigDecimal::bigDecimal(void)
{	
	this->contents = new char[2];
	*this->contents = '0';
	*(this->contents+1) = '\0';
	this->bits = 1;
}

/*
 * create an bigDecimal with its content is decimal char sequence.
 */
bigDecimal::bigDecimal(const char *decimal) {
	int errCode = this->validate(decimal);
	if (errCode!=OK) {
		this->throwExp(errCode);
	}
	this->bits = strlen(decimal);
	this->contents = new char[bits];
	strcpy(this->contents,decimal);
}

/*
 * release its memory, which called by compiler.
 */
bigDecimal::~bigDecimal(void)
{
	delete []contents;
}

/*
 * add two bigDecimal, return its total.
 */
bigDecimal& bigDecimal::operator +(const bigDecimal &rDecimal) {
	
	// calculate max number of bits for total, and set maxBits more than it 1. 
	int maxBits;
	if (this->bits > rDecimal.bits) {
		maxBits = this->bits + 1;
	} else {
		maxBits = rDecimal.bits + 1;
	}

	char* total = new char[maxbits+1];
	*(total+maxBits)='\0';
 
	bool carry = false;
	int lNum,rNum,lNumBitCnt=1,rNumBitCnt=1;
	
	// calculate total of big decimals.
	for (int cnt=1;cnt<maxBits;cnt++) {
		
		// lNum has added the highest bit.
		if (lNumBitCnt > this->bits) {
			lNum = 0;
		} else {
			lNum = *(this->contents + this->bits - lNumBitCnt) - '0';
		}
		
		// rNum has added the highest bit.
		if (rNumBitCnt > rDecimal.bits) {
			rNum = 0;
		} else {
			rNum = *(rDecimal.contents + rDecimal.bits - rNumBitCnt) - '0';
		}

		/*
		 * when there is a carry at highest bit, return an bigDecimal which directly instanciates by total char sequence. 
		 * Else, return an bigDecimal by char sequence which omits the first char of total.
		 */
		if (carry) {
			*(total+maxBits-cnt) = (rNum + lNum + 1)%10 + '0';
			carry = (rNum + lNum + 1)/10 != 0;
		} else {
			*(total+maxBits-cnt) = (rNum + lNum)%10 + '0';
			carry = (rNum + lNum)/10 != 0;
		}

		rNumBitCnt++;
		lNumBitCnt++;
	
	}
	
	bigDecimal* totalDecimal;
	// has carry bit at lower bit when adding.
	if (carry) {
		*total = '1';
		totalDecimal = new bigDecimal(total);
	} else {
		totalDecimal = new bigDecimal(total+1);
	}
	delete[] total;

	return *totalDecimal;

}

/*
 * validate input char sequence.
 * if input is null, return ERR_CODE_NULL,
 * if input is none, return ERR_CODE_NOTHING,
 * if input contains illegal characters(beside 0-9), return ERR_CODE_UNSUPPORT_NUM,
 * other, return OK.
 */
int bigDecimal::validate(const char* input) {
	if (input == NULL) {
		return ERR_CODE_NULL;
	}
	
	int len = strlen(input);	
	if (len==0) {
		return ERR_CODE_NOTHING;
	}

	for (int cnt=0;cnt<len;cnt++) {
		char c = *(input+cnt);
		if(c<'0'||c>'9') {
			return ERR_CODE_UNSUPPORT_NUM;
		}
	}

	return OK;
}

/*
 * throw exception to client when error occurs.
 */
void bigDecimal::throwExp(int errCode) {
	char* msg = NULL;
	switch(errCode) {
		case ERR_CODE_NULL:
			msg = "Warning!Passing parameter for bigDecimal is null.";
			break;
		case ERR_CODE_NOTHING:
			msg = "Warning!Passing parameter for bigDecimal is none.";
			break;
		case ERR_CODE_UNSUPPORT_NUM:
			msg = "Warning!Passing parameter for bigDecimal has illegal character.";
			break;
		default:;
	}
	if (msg) {
		throw std::exception(msg);
	}
}

/*
 * override output operator '<<' to print bigDecimal directly on console.
 */
std::ostream& operator <<(std::ostream &os, const bigDecimal& decimal) {
	os << decimal.contents;
	return os;
}

/*
 * override input operator '>>' to read bigDecimal directly on console. 
 */
std::istream& operator>>(std::istream& is, bigDecimal& decimal) {
	char* buf = new char[in_stream_buffer_size];
	is>>buf;
	int errCode = decimal.validate(buf);
	if(errCode!=OK){
		decimal.throwExp(errCode);
	}
	decimal.bits = strlen(buf);
	decimal.contents = new char[decimal.bits+1];
	strcpy(decimal.contents, buf);
	delete[] buf;
	return is;
}

/**************************************************************************************************************
 *   Main
 **************************************************************************************************************/
int main(void) {
	char key='y';
	while (key=='y') {
		try {
			bigDecimal a,b;
			std::cout<<"Input left operated decimal: ";
			std::cin>>a;
			std::cout<<"Input right operated decimal: ";
			std::cin>>b;
			std::cout<<"Total:"<<a<<"+"<<b<<"="<<a+b<<std::endl;
			std::cout<<"Calculate again?(y/n)";
			std::cin>>key;
		} catch (std::exception e) {
			std::cout<<e.what()<<std::endl;
			std::cout<<"Please type decimals again!"<<std::endl;
		}
	}
}

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。