Jump to content
  • Advertisement

Archived

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

Alpha_ProgDes

My function is giving BAD numbers

This topic is 5741 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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
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]

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

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!