This project is mainly GCD and validating the error from user input. I got the GCD working correctly, but not the errors. Here's guidelines to validate the errors.
-Provide a function to get a nonzero positive integer from the keyboard and return it to the caller.
int get_input()
-If input is not valid, the function should output an error message and repeat the input operation.
-Be sure your input function works correctly with invalid inputs. Even inputs that are not integers:123.456 (Should return 123)
abc (Should output error message and repeat input.)
Now here's the problem. Everything compiles with no problems. When I input zero for X, it moves on and ask for Y. Now, it's not suppose to do that. It's suppose to output an error message and asking me for a different input. Also, a similar problem with decimal numbers like 123.123. It just automatically ends the program with decimal numbers. Here is a sample output:
Enter integer X: 0
Please enter an integer greater than 0
123.456
Enter integer Y: Please enter an integer greater than 0
abc
Please enter an integer greater than 0
44
The GCD of 123 and 44 is 1
Here's what I have.
#include <stdio.h>
int gcd(int x, int y);
int gcd(int x, int y)
{
if (y == 0)
return x;
else
return gcd(y, x % y);
}
int get_input()
{
int x, y;
while(1)
{
if(scanf("%d", &x) != EOF)
{
if (x > 0)
return x;
}
if(scanf("%d", &x) != EOF)
{
if (y > 0)
return y;
}
else
{
printf("Input error\n");
printf("Please enter an integer greater than 0\n");
while(getchar() != '\n'); // Clear the input buffer
}
}
}
int main()
{
int x, y, common;
printf("This program computes the greatest common divisor\n");
printf("of positive integers X and Y, entered by the user.\n");
printf("Inputs must be integers greater than zero.\n\n");
printf("Enter integer X: ");
x = get_input();
printf("Enter integer Y: ");
y = get_input();
common = gcd(x,y);
printf("The GCD of %d and %d is %d\n", x, y, common);
return 0;
}
Any help getting me in the right direction is greatly appreciated. Thanks!