Let me brief you: I am trying to create a simple fraction calculator using a class named Fraction. I spent enough time trying to get the lowterms() member function to work. (still not sure if it does work, if you see a problem tell me) But the program still wouldn't output the correct answer. Anyways, i 'watched' the variables ff1.num and ff2.den in the member function getFrac() and it turns out they don't change, even though i'm promting for input. For example, if i created a constructor to set all objects data to 0, then call the function getFrac(), num and den are initialized, but ff1.num and ff2.den don't change; they still remain 0;![]()
.NOTE: den = denominator, num = numerator, gcd = greatest common divisor
I suspect that that's the biggest problem - that the second fraction the user enters ( ff1.num, ff2.num ) are not initilized to what hte user enters. thus, giving a totalaly wrong output. Why won't teh value of ff1.num and ff1.den change when prompted for input? thanksCode:#include <iostream.h> char oper; // for operation on fractions class Fraction { private: int num, den; // numerator and denominator public: void getFrac( Fraction ff1 ) { char misc; // character inbetween num and den cin >> num >> misc >> den >> oper >> ff1.num >> misc >> ff1.den; // <--PROBLEM HERE!!! } void add( Fraction ff1, Fraction ff2 ) { num = ff1.num*ff2.den + ff1.den*ff2.num; den = ff1.den*ff2.den; } void sub( Fraction ff1, Fraction ff2 ) { num = ff1.num*ff2.den - ff1.den*ff2.num; den = ff1.den*ff2.den; } void mul( Fraction ff1, Fraction ff2 ) { num = ff1.num*ff2.num; den = ff1.den*ff2.den; } void div( Fraction ff1, Fraction ff2 ) { num = ff1.num*ff2.den; den = ff1.den*ff2.num; } void display() { cout << num << '/' << den; } void lowterms(); }; void Fraction::lowterms() { enum testRun { didntRun, didRun }; testRun whileLoopRan = didntRun; for(int gcd = 2; gcd <= den/2; gcd++ ) { while(!(num%gcd) && !(den%gcd) ) { num = num / gcd; den = den / gcd; whileLoopRan = didRun; } if( whileLoopRan ) { gcd = 1; whileLoopRan = didntRun; } } } int main() { Fraction frac1, frac2, fracAns; char choice = 99; while( choice != 'n' && choice != 'N' ) { cout << "Enter fraction, operator, second fraction: "; frac1.getFrac( frac2 ); switch(oper) { case '+': fracAns.add(frac1, frac2); break; case '-': fracAns.sub(frac1, frac2); break; case '*': fracAns.mul(frac1, frac2); break; case '/': fracAns.div(frac1, frac2); break; default: cout << "\nIllegal operator."; continue; } fracAns.lowterms(); cout << "Answer = "; fracAns.display(); cout << "\nAgain(y/n)?: "; cin >> choice; } return 0; } // end main



LinkBack URL
About LinkBacks




. wow, i love when you struggle with somthing fo so long and then the answer is simple. love it and then i say to myselt "what the hec!" i didn't see that. "Now i know! cheers.