Hi there, have been working on final question to course work and have come across some problems with getting my modulus operator to work.
I am trying to find the GCD of two integers given and have gotten up to this:
#include <iostream>
#include <cmath>
usingnamespace std;
int main()
{
double num1, num2, remainder, d, a, b;
cout<<"This program determines the Greatest Common Denominator"<<endl;
cout<<"in all numbers."<<endl<<endl;
cout<<"Please input the two numbers you would like to calculate"<<endl;
cout<<"the GCD for."<<endl<<endl;
cout<<"num1:";
cin>>num1;
cout<<"num2:";
cin>>num2;
remainder = a%d;
while (remainder > 0){
a=b;
b=remainder;
remainder=(a%b);}
cout<<b;
system("PAUSE");
return EXIT_SUCCESS;
}
Any help on my misuse of the modulus operator would be greatly appreciated.
A really good habit to start doing is to initialize ( or give a value to) every variable you create. If you don't, it will have a value of -909382093842390, or something like that. Just set them to zero. a = 0, b = 0, //....and so on...
So when you are doing a % b , you're really working with those large negative numbers.
And you cin into num1 and num2 , but you don't use them anywhere.
d is not used anywhere.
I think you have the idea correct. You just need to use the right variables and stuff.
And you should also consider the possibility when remainder = a % b....is equal to zero at the start, and the while loop is never executed. What should "b" be then?