I am trying to learn clear and concise C++. Currently I'm learning classes in school, and to practice I have made a Fraction class.
I'd appreciate any help regarding style, cleanliness or anything else that would be good to know.
(I know using namespace std;
is frowned upon, but it's required in our course.)
#include <iostream>
using namespace std;
class Fraction {
int numerator, denominator;
private:
int gcd(int a, int b) {
while (a != b) {
if (a > b)
a -= b;
else
b -= a;
}
return a;
}
public:
Fraction (int, int);
double decimal();
string fraction();
Fraction add(Fraction);
Fraction subtract(Fraction);
Fraction multiply(Fraction);
Fraction divide(Fraction);
};
int main() {
Fraction f = {2,3};
cout << f.decimal() << endl;
Fraction k = {1,4};
Fraction d = {1,3};
Fraction result = k.add(d).add(f);
cout << result.fraction() << endl;
return 0;
}
Fraction::Fraction(int n, int d) {
numerator = n / gcd(n, d);
denominator = d / gcd(n, d);
}
string Fraction::fraction() {
return to_string(numerator) + "/" + to_string(denominator);
}
double Fraction::decimal() {
return (double)numerator / (double)denominator;
}
Fraction Fraction::add(Fraction f) {
return Fraction(numerator * f.denominator + f.numerator * denominator, denominator * f.denominator);
}
Fraction Fraction::subtract(Fraction f) {
return Fraction(numerator * f.denominator - f.numerator * denominator, denominator * f.denominator);
}
Fraction Fraction::multiply(Fraction f) {
return Fraction(numerator * f.numerator, denominator * f.denominator);
}
Fraction Fraction::divide(Fraction f) {
return Fraction(numerator * f.denominator, denominator * f.numerator);
}
decimal
function here? \$\endgroup\$decimal
. I'll concede that something liketoDouble
might be more technically correct... \$\endgroup\$hex()
function is added that returns a string hex representation, orbinary()
, oroctal()
? They would be pretty “common” to add I think, and would totally mismatch with the legacydecimal()
function in place. A cast operator would be more suited here. \$\endgroup\$