Archived

This topic is now archived and is closed to further replies.

Alpha_ProgDes

My function is giving BAD numbers

Recommended Posts

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.

Share this post


Link to post
Share on other sites
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

Share this post


Link to post
Share on other sites