Monday, May 24, 2010

C++ program help?

I am trying to write a program that asks for two integers and then finds the greatest common factor between them. IN C++


I copy paste it and it doesn’t work? PLZz HELP


Thank you





......................................





#include %26lt;iostream%26gt;


using namespace std;


int factor(int a, int b);





int main()


{


int x, y;





cout %26lt;%26lt; "This program allows calculating the factor\n";


cout %26lt;%26lt; "Value 1: ";


cin %26gt;%26gt; x;


cout %26lt;%26lt; "Value 2: ";


cin %26gt;%26gt; y;





cout %26lt;%26lt; "\nThe Greatest Common factor of "


%26lt;%26lt; x %26lt;%26lt; " and " %26lt;%26lt; y %26lt;%26lt; " is " %26lt;%26lt; factor(x, y) %26lt;%26lt; endl;





return 0;


}





int factor(int a, int b)


{


while( 1 )


{


a = a / b;


if( a == 0 )


return b;


b = b / a;


if( b == 0 )


return a;


}


}

C++ program help?
Hi your main() functions good and the idea behind how you work out the greatest common factor is also fine but you need to make sure when you do the division that the larger of the 2 numbers is divded by the other.





A simple check if a is greater than b allows you to know when to to divide a/b or b/a. The case where they are both equal to each other can be handled by either.





int factor(int a, int b)


{


int ret_val=0;





/* CASE 1 a %26gt; b */


if (a %26gt; b)


{


ret_val = a/b;


}


else /* CASE 2 b %26gt;= a */


{


ret_val = b/a;


}





return (ret_val);


}





Things to note include:





- I have removed the forever loop while(1) as it wasnt doing anything because you would return from the function.





- avoid returns in the middle of a function, to get around this I have a return value, ret_val, that only returns on the end of the function.





- I would add a check for 0 when the values are read in to make sure that you dont do a divide by 0.





Good luck.
Reply:You have to include math.h





So add this at the top of your program:





#include %26lt;math.h%26gt;


No comments:

Post a Comment