Define a class, which implements arithmetic with arbitrary precision - Programmers Heaven

#### Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

#### Categories

Welcome to the new platform of Programmer's Heaven! We apologize for the inconvenience caused, if you visited us from a broken link of the previous version. The main reason to move to a new platform is to provide more effective and collaborative experience to you all. Please feel free to experience the new platform and use its exciting features. Contact us for any issue that you need to get clarified. We are more than happy to help you.

# Define a class, which implements arithmetic with arbitrary precision

Posts: 2Member
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.
Well, to do arbitrary precision arithmetic in C++, I think we need to develop a class such as 'Big Float'. I find it hard to believe they'd expect a beginner like me to do this as it's really a job for a mathematical specialist.
[code]#include "stdafx.h"
#include
#include
#include
#include
#include
using namespace std;

class Number{
private:
string _numbers;
public:
Number(){}
Number(const string& num) : _numbers(num){}
friend string ConvertToString(double value);
void print();
Number operator+(Number rhsNumber);

};
Number Number::operator+( Number rhsNumber)
{
Number temp;
temp._numbers =ConvertToString(atof(this->_numbers.c_str())+atof(rhsNumber._numbers.c_str()));
return temp;
}
void Number::print()
{
cout<<_numbers<<endl;
}
string ConvertToString(double value)
{
std::stringstream ss;
ss << setprecision(15)<<value;
return ss.str();
}
int _tmain(int argc, _TCHAR* argv[])
{
Number a="1.21111111111111111111111111111111111112222";
Number b="2.1111111";
Number c=a+b;
c.print();
system("PAUSE");
return 0;
}
[/code]
The thing is: suppose I'm an user. So I can use a Number object with arbitrary length, after computing the result should be saved with the precision that I've gave the Number object (in this situation the length of result should be saved).
But in my program it depends on setprecision(int n). The user has no choice. and it's a pointless.