Advertisement Jump to content
Sign in to follow this  
Enigma_

Can't seem to figure out the problem

This topic is 3373 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

Hey, I was making this class for presenting fractions. To write a fraction in simple form, i formed this function called gcd, but I am getting a really weird result when I try the program. Here's my code. #include <iostream> using std::cout; using std::cin; int gcd(int n, int d) { cout << "\nn = " << n << " d = " << d; if (d % n == 0) { return n; } else { cout << "\nd % n = " << d % n; gcd((d % n), n);} } int main() { int x = 0; // first number int y = 0; // second number int hcf = 0; cout << "Enter 1st number : "; cin >> x; // store first number cout << "\nEnter 2nd number: "; cin >> y; // store second number hcf = gcd (x , y); // store gcd in hcf cout << "\n\nHCF of " << x << " & " << y << " = " << hcf; // print gcd } The weird thing is that the result is always 4...In function gcd, if I add a line "cout << n " before "return n", it gives the correct gcd, but the return value of the function is always 4. Any idea as to why this is happening? thanks a lot

Share this post


Link to post
Share on other sites
Advertisement
You've forgotten a return statement:


int gcd(int n, int d) {
cout << "\nn = " << n << " d = " << d;
if (d % n == 0) {
return n;
} else {
cout << "\nd % n = " << d % n;
return gcd((d % n), n); // <<-- here
}
}




If you're using Visual Studio, a C4715 warning should have been issued.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

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

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!