Can't seem to figure out the problem
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
You've forgotten a return statement:
If you're using Visual Studio, a C4715 warning should have been issued.
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.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement