Hi everyone!
I'm reading a book and doing some exercises in this book. One of them is: define a class, which implements arithmetic (+, -, /, *) with arbitrary precision. This is a new type with just some arithmetic operations. With type double we also can do some arithmetic but with a definite precision.
May someone get me started. I need an idea to get into.

3
Contributors
7
Replies
8
Views
7 Years
Discussion Span
Last Post by svatstika

This might help.

``````int max(int a, int b){

return a>b ? a:b;

}
int min(int a, int b){

return a<b ? a:b;

}``````

Upvote my post if they helped.

If you want to read a line.

``````void line(char*Filename,int maxline){

ifstream file;
file.open(Filename);

string input,output;

for(int x = 0; x < maxline; x++)
{
getline(file,input);

output += string(input + "\n");

}
cout<<output<<endl;
}``````

First you need to be able to represent data in arbitrary length. One way to do that is use a std::vector<int> numbers or even std::string. Personally, I would choose the std::strings, because its easier to work with.

So lets define such a type :

``````class Number{
private:
std::string _numbers;
public:
Number(){}
Number(const std::string& num) : _numbers(num){}
};``````

Now you need to define the operator interface, you can either use overloaded operators or member functions. I would suggest you to have private member function and implement the overloaded operators like so :

``````class Number{
private:
std::string _numbers;
public:
Number(){}
Number(const std::string& num) : _numbers(num){}
std::string operator+(const std::string& rhsNumber)const{ return _add(rhsNumber);}
//subtract operator
//divide operator
std::string operator/(const std::string& rhsNumber)const{return _divide(rhsNumber);}
//multiply operator
std::string operator*(const std::string& rhsNumber)const{return _multiply(rhsNumber);}
//negation operator
std::string operator-()const;
private:
//helper function
string _multiply(std::string rhsNumber)const{/*add logic here */}
string _divide(std::string rhsNumber)const{/*add logic here */}
};``````

The thing is: to implement arithmetic, we need to convert rhsNumber._numbers to type double (for example atof(rhsNumber)) and then work with them. And as I said at the first post. With two number type double we only can implement arithmetic with a define precesion.

``````string Number::_add(std::string rhsNumber)const{