Struct decimal number

I have problem making structure decimal number in c++. To be more specific my greatest issue is how to overload (input) >> operator and operation of fast powering. The number needs to be represented by two lists, first list has to contain int part of number ond the secound decimal part. What is the best way to separate number aaa.bbb on int aaa and int bbb in reasonable time, and put them in separate lists? also if the last k digits of decimal part are 0 I need to cut them off.

basic class looks like

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
  template <typename Int>
class Dec {
public:

  Dec(const Int& before = Int(1),
           const Int& after = Int(0));

  Int before() const;
  Int after() const;

  Dec& operator+= (const Dec<Int>& rhs);
  Dec& operator-= (const Dec<Int>& rhs);
  Dec& operator*= (const Dec<Int>& rhs);

  Dec& operator*= (const Int& scaleFactor);

private:
  Int mbefore, mafter;

};
What is the best way to separate number aaa.bbb on int aaa and int bbb in reasonable time
Here's one way, assuming you can directly manipulate what you tell the user to enter:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// Example program
#include <iostream>
#include <string>

int main()
{
    using namespace std;
    
    cout << "Enter number: ";
    
    int left;
    char decimal_point;
    int right;
    
    cin >> left;
    cin >> decimal_point;
    cin >> right;
    
    cout << "You entered: " << left << decimal_point << right << '\n'; 
}

Enter number: 1234.5678
You entered: 1234.5678


Of course, it will be larger in complexity after you add more dynamic behavior and error handling, at which point it might just be easier to parse the input as a string, and then break it up yourself (hint: strings and stringstreams).
Last edited on
Dec& operator*= (const Dec<Int>& rhs);

You are going to be hard pressed to make that function work. Eventually, you will have to do some rounding if your decimal components are represented by ints.
The number needs to be represented by two lists, first list has to contain int part of number ond the secound decimal part

...
1
2
private:
  Int mbefore, mafter;


So which is it? A list or an int?

How will you represent 1/3, whose decimal fraction repeats forever?

I think it would be far better to represent the digits with a vector rather than a list.
I have created my own list, that I want to use for this problem. I will input numbers in format aaa.bbb where aaa and bbb are ints
Topic archived. No new replies allowed.