Confused with adding fractions

Instructions are: implement a simple class called the Rational class that can used to represent fractions. These objects hold an integer values that may be be zero or above, but should not go negative Be sure to include the following members for Rational:

a private member variables to hold the numerator and denominator values
a default constructor
an overloaded constructor that accepts two values for an initial fraction
member functions add(), sub(), mul(), div(), less(), eq(), and neq(). (less should return true if the object is less than the argument)
a member function to return the current numerator and denominator.
a member function that accepts an argument of type ostream that writes the fraction to that open output stream.
Do not let either numerator or denominator stored value go negative. Display an error message on the user terminal if any of member functions try to force a negative count value.

This is what I have so far, but I'm confused as to how to move forward. I'm still very much a beginner.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
 #include <fstream>
#include <iostream>
#include <stdlib.h>
#include <time.h>

using namespace std;

class Rational
{
public:
    Rational(int n = 0, int d = 1);
    void print();
    void add(float value);
    void sub(float value);
    void mult(float value);
    void div (float value);
    void less(bool = true);
    void eq(float value);
    void neq(float value);
private:
    int num, den;
    void reduce();
};

Rational::Rational(int n, int d)
{
    num = n;
    if (d <= 0)
    {
        cout << "Error, denominator is equal to 0 or negative" << endl;
        exit(0);
    }
    else
        den = d;
}

int gcd(int a, int b)
{
    if(a == 0)
        return b;
    else
        return gcd(b%a, a);
}
gcd is available in the language, you don't have to reinvent it.
use <ctime> and <cstdlib> ... the headers you have are from C, not C++ (they work for small programs, but its not good practice)

your next step is to start filling things out.
how about print()? Can you do that, to show that when you create one with the constructor that your fraction is set up properly?

you also need a default constructor, so get that working.

then build on it, make 2 fractions and, for example, add them, print the result, see if that works.

basically, your next steps are to fill out a check box for the requirements, test just that new code, get it working, repeat for all the check boxes. Because of the test and get it working idea, I suggested doing print first so you can see that things work.

review the requirements carefully.
Do not let either numerator or denominator stored value go negative
did you do this? (no, looks like num can be any value in your current code...)

your topic says confused about adding... how do you add fractions, on paper? You get them to the same denominator, and then you add the numerators. 1/2 + 1/2 = 2/2 = 1, right? Most of the logic there will be to get them to that common denominator. DO you recall how to do this from your early school math classes?
Last edited on
Here is a bit more of a start. Add the gcd stuff in later - just take your recommended pencil and paper plan and then and only then write a few lines of code and then and only then test it before moving on.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#include <iostream>

class Rational
{
private:
    int numerator{0};
    int denominator{1};
    
public:
    Rational() = default;
    Rational(int, int);
    ~Rational(){};
    
    void add(const Rational&, const Rational&);
    
    bool isValid();
    void print();
};

Rational::Rational(int num, int den)
{
    numerator = num;
    denominator = den;
    
    if( !(isValid()) )
        std::cout << "Error: Invalid fraction\n";
}

void Rational::add(const Rational& ra, const Rational& rb)
{
    numerator = ra.numerator * rb.denominator + rb.numerator * ra.denominator;
    denominator = ra.denominator * rb.denominator;
}

void Rational::print()
{
    if( isValid() )
        std::cout << numerator << '/' << denominator << '\n';
    else
        std::cout << "Unprintable\n";
}

bool Rational::isValid()
{
    if( denominator == 0 || numerator < 0 || denominator  < 0 )
        return false;
    else
        return true;
}

int main()
{
    //    Rational a;
    //    a.print();
    
    Rational b(2,3);
    b.print();
    
    Rational c(4,9);
    c.print();
    
    // Rational rat(1,0);  Rational rat(1,-9);  Rational rat(-1,9);  Rational rat(-1,-9);
    //    rat.print();
    
    Rational sum;
    sum.add(b,c);
    sum.print();
    
    return 0;
}
Here's a fraction class I already had. NOTE it does not fulfill all the requirements (eg it works with -ve fractions, add(), sub() etc are implemented as operator overloads etc.

However, it should give a starting point.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
#include <iostream>
#include <numeric>
#include <iomanip>

class fraction {
public:
	fraction(int n, int d) : num(n), den(d) {
		reduce();
	}

	explicit fraction(int i = 0) : num(i), den(1) {}

	fraction(const fraction& fr) = default;
	fraction(fraction&& fr) = default;
	fraction& operator=(const fraction& fr) = default;
	fraction& operator=(fraction&& fr) = default;

	fraction& operator=(int i)
	{
		num = i;
		den = 1;

		return *this;
	}

	fraction& reduce()
	{
		if (den == 0) {
			num = 0;
			den = 1;
			throw std::overflow_error("Denominator zero exception");
		}

		if (den < 0) {
			num *= -1;
			den *= -1;
		}

		if (den > 1)
			if (const int g = std::gcd(num, den); g != 1) {
				num /= g;
				den /= g;
			}

		return *this;
	}

	fraction& invert()
	{
		std::swap(num, den);
		return *this;
	}

	fraction& neg()
	{
		num *= -1;
		return *this;
	}

	fraction operator-() const
	{
		fraction f(*this);

		return f.neg();
	}

	fraction& operator+=(const fraction& fr)
	{
		const int l = std::lcm(fr.den, den);

		num = l / den * num + l / fr.den * fr.num;
		den = l;
		return reduce();
	}

	fraction& operator+=(int i)
	{
		return *this += fraction(i);
	}

	fraction operator+(const fraction& fr) const
	{
		fraction f(*this);

		return f += fr;
	}

	fraction operator+(int i) const
	{
		fraction f(*this);

		return f += i;
	}

	fraction& operator*=(const fraction& fr)
	{
		num *= fr.num;
		den *= fr.den;
		return reduce();
	}

	fraction& operator*=(int i)
	{
		return *this *= fraction(i);
	}

	fraction operator*(const fraction& fr) const
	{
		fraction f(*this);

		return f *= fr;
	}

	fraction operator*(int i) const
	{
		fraction f(*this);

		return f *= i;
	}

	fraction& operator/=(const fraction& fr)
	{
		fraction f(fr);

		return *this *= f.invert();
	}

	fraction& operator/=(int i)
	{
		fraction f(i);

		return *this *= f.invert();
	}

	fraction operator/(const fraction& fr) const
	{
		fraction f(fr);

		return f.invert() *= *this;
	}

	fraction operator/(int i) const
	{
		fraction f(i);

		return f.invert() *= *this;
	}

	fraction& operator-=(const fraction& fr)
	{
		fraction f(fr);

		return *this += f.neg();
	}

	fraction& operator-=(int i)
	{
		fraction f(i);

		return *this += f.neg();
	}

	fraction operator-(const fraction& fr) const
	{
		fraction f(fr);

		return f.neg() += *this;
	}

	fraction operator-(int i) const
	{
		fraction f(i);

		return f.neg() += *this;
	}

	fraction& operator++()	//Prefix
	{
		return *this += 1;
	}

	fraction operator++(int) // Postfix
	{
		fraction f(*this);
		++(*this);
		return f;
	}

	fraction& operator--()	//Prefix
	{
		return *this -= 1;
	}

	fraction operator--(int) // Postfix
	{
		fraction f(*this);
		--(*this);
		return f;
	}

	bool operator==(const fraction& fr) const
	{
		return (fr.num == num) && (fr.den == den);
	}

	bool operator!=(const fraction& fr) const
	{
		return !(*this == fr);
	}

	bool operator>(const fraction& fr) const
	{
		const int l = std::lcm(fr.den, den);

		return ((l / den * num) > (l / fr.den * fr.num));
	}

	bool operator <=(const fraction& fr) const
	{
		return !(*this <= fr);
	}

	bool operator>=(const fraction& fr) const
	{
		return (*this == fr) || (*this > fr);
	}

	bool operator<(const fraction& fr) const
	{
		return !(*this >= fr);
	}

	bool operator==(int i) const
	{
		return *this == fraction(i);
	}

	bool operator!=(int i) const
	{
		return !(*this == i);
	}

	bool operator>(int i) const
	{
		return *this > fraction(i);
	}

	bool operator<=(int i) const
	{
		return !(*this > i);
	}

	bool operator>=(int i) const
	{
		return *this >= fraction(i);
	}

	bool operator<(int i) const
	{
		return !(*this >= i);
	}

	friend std::ostream& operator<<(std::ostream& os, const fraction& fr);
	friend std::istream& operator>>(std::istream& is, fraction& fr);

private:
	int num = 0;
	int den = 1;
};

inline bool operator==(int i, const fraction& fr)
{
	return fr == i;
}

inline bool operator!=(int i, const fraction& fr)
{
	return fr != i;
}

inline bool operator>(int i, const fraction& fr)
{
	return fr < i;
}

inline bool operator>=(int i, const fraction& fr)
{
	return fr <= i;
}

inline bool operator<(int i, const fraction& fr)
{
	return fr > i;
}

inline bool operator<=(int i, const fraction& fr)
{
	return fr >= i;
}

inline fraction operator+(int i, const fraction& fr)
{
	return fr + i;
}

inline fraction operator*(int i, const fraction& fr)
{
	return fr * i;
}

inline fraction operator/(int i, const fraction& fr)
{
	fraction f(fr);

	return f.invert() * i;
}

inline fraction operator-(int i, const fraction& fr)
{
	fraction f(fr);

	return f.neg() + i;
}

std::ostream& operator<<(std::ostream& os, const fraction& fr)
{
	if ((abs(fr.num) > fr.den) && (fr.den > 1))
		os << fr.num / fr.den << "+" << fraction(abs(fr.num) % fr.den, fr.den);
	else {
		os << fr.num;
		if (fr.den != 1)
			os << "/" << fr.den;
	}

	return os;
}

std::istream& operator>>(std::istream& is, fraction& fr)
{
	auto getden = [&]() {
		is >> fr.den;
		if (fr.den == 0) {
			is.setstate(std::ios::failbit);
			fr = 0;
		}
	};

	int n = 0;

	fr = 0;
	is >> n;

	if (auto ch = is.peek(); (ch == '+') || (ch == '/')) {
		is.get();
		if (ch == '+') {
			is >> fr.num;
			if (is.peek() == '/') {
				is.get();
				getden();
				if (is.good())
					fr = (n < 0) ? n - fr : n + fr;
			}
		} else {
			fr.num = n;
			getden();
		}
	} else
		fr = n;

	fr.reduce();

	return is;
}

int main()
{
	fraction f1(2, 3);
	fraction f2(3, 4);

	fraction f;

	while ((std::cout << "Enter a fraction: ") && !(std::cin >> f)) {
		std::cout << "Invalid fraction" << std::endl;
		std::cin.clear();
		std::cin.ignore(1000, '\n');
	}

	fraction f3 = f;

	std::cout << f3 << std::endl;

	std::cout << f1 << " + " << f2 << " = " << f1 + f2 << std::endl;
	std::cout << -f1 << " - " << f2 << " = " << -f1 - f2 << std::endl;
	std::cout << f1 << " * " << f2 << " = " << f1 * f2 << std::endl;
	std::cout << -f1 << " + " << f2 << " = " << -f1 + f2 << std::endl;
	std::cout << f1 << " / " << f2 << " = " << f1 / f2 << std::endl;
	std::cout << f2 << "/ " << f1 << " = " << f2 / f1 << std::endl;
	std::cout << "6 - " << f3 << " + " << f1 << " + " << f2 << " = " << 6 - f3 + f1 + f2 << std::endl;
	std::cout << f1 << " > " << f2 << " = " << std::boolalpha << (f1 > f2) << std::endl;
	std::cout << f2 << " > " << f1 << " = " << std::boolalpha << (f2 > f1) << std::endl;

	std::cout << f3 << " += " << f1 << " = ";

	f3 += f1;
	std::cout << f3 << std::endl;

	std::cout << f3 << " -= " << f2 << " = ";

	f3 -= f2;
	std::cout << f3 << std::endl;
}

Put the assignment in the code as comments. Then move the comments around to the places that implement them.

If the value can't go negative then what should neg() do? I suspect it should just print an error message (unless the value is zero).

You'll see below that I recommend changing the functions so they take a Rational as parameter and return a Rational as the result. The reason is that there's a good chance that a future assignment will be to change this program so that it uses "overloaded operators". For example, an overloaded "+" operator will let you write
1
2
3
4
Rational a(1,2);
Rational b(2,3);
Rational c;
c = a + b; // overloaded + operator 


I urge you to write a private normalize() method. This will reduce the fraction al lowest terms. If you add negative values in the future, it could ensure that the numerator is always positive.

Write the method to print the Rational next. Then write a main() program that creates a couple rationals and prints them out.

Then write one of the methods (maybe mul()). Change your main program to call mul and print the results.

Then add the rest of the methods one by one and keep changing the main program to test them.

Here are some changes to your code to show what I mean.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#include <fstream>
#include <iostream>
#include <stdlib.h>
#include <time.h>

using namespace std;

// TODO: a default constructor

// TODO: a member function to return the current numerator and denominator.

// TODO: a member function that accepts an argument of type ostream that
// writes the fraction to that open output stream.

// Do not let either numerator or denominator stored value go
// negative. Display an error message on the user terminal if any of
// member functions try to force a negative count value.
																		      
class Rational
{
public:

    // an overloaded constructor that accepts two values for an
    // initial fraction
    // WARNING: This isn't quite what's asked for. 
    Rational(int n = 0, int d = 1);
    void print();
    // member functions add(), sub(), mul(), div(), less(), eq(), and
    // neq(). (less should return true if the object is less than the
    // argument)
    // WARNING: mult() should be mul()
    // Also, I think these should take a Rational as the argument and
    // return a Rational as the result:
    // For example Rational add(Rational value);
    void add(float value);
    void sub(float value);
    void mult(float value);
    void div (float value);
    void less(bool = true);
    void eq(float value);
    void neq(float value);	// WARNING: conflicts w/ requirement
				// that value doesn't go negative
private:
    // a private member variables to hold the numerator and
    // denominator values
    int num, den;
    void reduce();
};

Rational::Rational(int n, int d)
{
    num = n;
    if (d <= 0)
    {
        cout << "Error, denominator is equal to 0 or negative" << endl;
        exit(0);
    }
    else
        den = d;
}

int gcd(int a, int b)
{
    if(a == 0)
        return b;
    else
        return gcd(b%a, a);
}

I urge you to write a private normalize() method. This will reduce the fraction al lowest terms. If you add negative values in the future, it could ensure that the numerator is always positive.


if I were a user I might like to have this public. Any reasoning for being private? (curiosity...)
Any reasoning for being private? (curiosity...)
None that's very good. :)

In theory, the class would guarantee that an instance was always normalized, so a client shouldn't need to call it... in theory.... And if they do, it would just be wasting time because the Rational would already be normalized.

It should probably be protected instead of private.
Topic archived. No new replies allowed.