Reputation: 96
My program is supposed to simplify the num and denom. But I have to use a Class, and use a display function to display my final result but everytime i display it. It gives me 82 for num and 21305... for den. Its like its not getting the number from Fraction::set.
Can anyone explain to me what I'm doing wrong and what I am not understanding from using a Class please. Thank you and advance.
#include <iostream>
using namespace std;
class Fraction
{
int num, den;
public:
void set(int,int);
void display();
};
int main(void) {
Fraction fraction;
int num, den;
cout << "Fraction Simplifier" << endl;
cout << "===================" << endl;
cout << "Numerator : ";
cin >> num;
cout << "Denomenator : ";
cin >> den;
cout << endl;
fraction.set(num, den);
fraction.display();
cout << endl;
return 0;
}
void Fraction::set(int num, int den)
{
int i;
for( i = num * den; i > 1; i--)
{
if(den % i == 0 && num % i == 0)
{
den/=i;
num/=i;
}
}
}
void Fraction::display()
{
cout << num << endl;
cout << den << endl;
}
Upvotes: 0
Views: 147
Reputation: 956
In your definition of Fraction::set you are passing in variables num and den. Since these variables have the same name as the member variables Fraction::num and Fraction::den they are 'hiding' the member variables.
In your function you never actually use the member variables, you only use and modify the variables passed in, and the member variables remain uninitialized to whatever values the program had for them before starting.
You might have better luck using different names for the variables passed in to the set function.
Ex.
void Fraction::set(int numValue, int denValue)
{
// format the values that were passed in
int i;
for( i = numValue * denValue; i > 1; i--)
{
if(denValue % i == 0 && numValue % i == 0)
{
denValue/=i;
numValue/=i;
}
}
// store the values in the class
num = numValue;
den = denValue;
}
There are other concerns and issues and best practices that you might want to look into, but that would be a question for the CodeReview forum.
Upvotes: 0
Reputation: 385144
Inside Fraction::set
, whenever you refer to num
or den
, it's to the function arguments.
At the end, you probably want to "save" those values to the member variables, using this->
to disambiguate†:
this->num = num;
this->den = den;
† It's not really disambiguation, but y'know.
Upvotes: 1