My function is giving BAD numbers

Started by
2 comments, last by Alpha_ProgDes 21 years, 6 months ago
this is my code:
  
#include <iostream>

#include <stdlib.h>

using namespace std;

int GCD (int, int);

int main ()
{
 static int num;
 static int den;

 cin >> num >> den;

 cout << num << " " << den << endl;

 GCD (num, den);

 cout << GCD(num,den) << endl;

 num /= GCD (num,den);
 den /= GCD (num,den);

 cout << num << " " << den << endl;

 system("PAUSE");
 return 0;
}

int GCD (int numerator, int denominator)
{
 int r, gCD;
 while (r != 0 ){
       if (r == 1){

          cout << "Already Simpilfied." << endl;
          break;
       }
       else if (numerator < denominator){
            r = denominator % numerator;
            denominator = numerator;
            numerator = r;
       }
       else if (numerator > denominator){
            r = numerator % denominator;
            numerator = denominator;
            denominator = r;
       }
 }
 if (r == 1)
    return gCD =1;
 else if (numerator < denominator){
      gCD = denominator;
      return gCD;
 }
 else if (numerator > denominator){
      gCD = numerator;
      return gCD;
 }
}
  
and this is the output:
  
36 21
36 21
3
12 1
Press any key to continue . . .
  
that number "1" is supposed to be denominator but it''s supposed to say "7" instead. but no matter what numbers i put i keep getting 0 or 1. someone please help.

Beginner in Game Development?  Read here. And read here.

 

Advertisement
I get the correct result, so I'm guessing it's that you forgot to set a value for r before your loop.

int r, gCD;
r = -1;
while (r != 0 )...

Shad


[edited by - ShadowCoder on October 1, 2002 1:29:33 AM]
thanks i''m working on my class and it''s one of the member functions.
and that''s giving me more trouble.....

Beginner in Game Development?  Read here. And read here.

 

One thing I''m finally starting to learn is this:

you need to make an algorithm, some plan of what you need and how to put it together

and

learning data types, and variables, etc... is great but it''s hard to code all that stuff without some knowledge of data structure and operation precedence....

beginner at work, be gentle :D

Beginner in Game Development?  Read here. And read here.

 

This topic is closed to new replies.

Advertisement