-
gcd
Why is this code returning the wrong gcd?
Code:
#include <iostream>
using namespace std;
int gcd(int a,int b);
int main()
{
double a = 0;
double b = 0;
cout << "Enter two integers and I will report their gcd: " << endl;
cin >> a,b;
cout << gcd(a,b) << endl;
return 0;
}
int gcd(int a, int b)
{
while ( b !=0 )
{
int t = b;
b = a % b;
a = t;
}
return a;
}
-
You cannot use commas like that. Read in a and b separately. Then try again and see if it works.
-
int t is being declared multiple times... each time through the loop. Define it once outside the loop, then assign a value to it each time through the loop. :)
Code:
int gcd(int a, int b)
{
int t;
while ( b !=0 )
{
t = b;
b = a % b;
a = t;
}
return a;
}
-
>> int t is being declared multiple times
That doesn't matter in this case because it is being assigned to b immediately either way.
-
Ah, I read in the variables separately and it worked. Thanks much!