Public Group

#### Archived

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

# 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.

## 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 on other sites
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 )...

[edited by - ShadowCoder on October 1, 2002 1:29:33 AM]

##### Share on other sites
thanks i''m working on my class and it''s one of the member functions.
and that''s giving me more trouble.....

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

• 48
• 12
• 10
• 10
• 9
• ### Forum Statistics

• Total Topics
631375
• Total Posts
2999660
×