Question

I have to write 2 different numbers in two textboxes, and with a button calculate the GCD, but when I run it, the button does nothing.

            int x = Convert.ToInt16(txtNum1.Text);
            int y = Convert.ToInt16(txtNum2.Text);

            int num1, num2;
            int residuo;
            if (x < y)
            {
                num1 = y;
                num2 = x;
            }
            else
            {
                num1 = x;
                num2 = y;
            }
            do
            {
                residuo = num1 % num2;

                if (residuo == 0)
                {
                    txtMCD.Text = num2.ToString();
                }
                else
                {
                    num1 = num2;
                    num2 = residuo;
                }      
            } while (residuo == 0);

X and y are both numbers writen in the textboxes, I use num1 and num2 to save the value of x and y in order that num1 is the higher, and num2 the lesser. Any ideas?

Was it helpful?

Solution

Your termination condition is incorrect. It should be while (residuo != 0). As it is, you either terminate the loop after one iteration, or you are in an infinte loop.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top