We've just learned classes and I'm still pretty confused about them.
Here is my code:
I'm not done with my code yet. I plan to add a private member function to reduce the fraction. But I want to fix this problem first. Also, any other corrections are welcomed.
/>
Here is my code:
#include<iostream>
using namespace std;
class fraction
{
private:
void reduce()
{}
int num, denom;
public:
fraction()
{
num = 0;
denom = 1;
}
fraction(int n, int d)
{
num = n;
if (d = 0)
{ cout << "Can't have a zero denominator!" << endl;
}
else
{denom = d;
}
}
fraction plus(fraction second)
{second.num = (num * second.denom) + (second.num *denom);
second.denom = denom * second.denom;
return second;
}
fraction minus(fraction second)
{second.num = (num * second.denom) - (second.num * denom);
second.denom = denom * second.denom;
return second;
}
fraction times(fraction second)
{second.num = num * second.num;
second.denom = denom * second.denom;
return second;
}
fraction divides(fraction second)
{second.num = num * second.denom;
second.denom = denom * second.num;
return second;
}
double toDecimal()
{ double decimal = (double)num/denom;
return decimal;}
void input()
{char div, op;
cout << "Please enter a fraction in x/y form: ";
cin >> num >> div >> denom;
cout << endl;
cout << "Please enter an operation (*, -, *, /): ";
cin >> op;
if (op == '+')
{fraction plus(num, denom);}
else if (op == '-')
{fraction minus(num, denom);}
else if (op == '*')
{fraction times(num, denom);}
else if (op == '/')
{fraction divides(num, denom);}
else {cout << "That is not a valid operation!" << endl;
exit(1);}
}
void output()
{
cout << num/denom;
}
};
int main()
{ int myFraction = 1/10;
fraction f, frac;
fraction(1, 10);
f.input();
frac = frac.plus(f);
frac.toDecimal();
cout << "1/10 + " << f.output() << " = " << ". " << "which is also " << toDecimal() << endl; //This is WRONG. How can I call my output function and toDecimal function from the class?
return 0;
}
I'm not done with my code yet. I plan to add a private member function to reduce the fraction. But I want to fix this problem first. Also, any other corrections are welcomed.