-
Simplifying Fractions
Hello,
I appreciate that this is probably a stupid question but I'm new to programming so please go easy on me!
I'm writing a program that finds the gcd of two numbers then returns a simplified fraction. I have a main function and a gcd function. The gcd function is done and is fine, but I don't know how to use the result in my gcd function in my main function to divide the numerator and denominator by the gcd! I don't even know if that's what I'm supposed to do!
Any help would be awesome. Thanks.
-
Can you post the code you currently have?
-
You can return one value from the gcd function. Any other number you want changed in the gcd function, with lasting effect, will have to be a number brought into the gcd function via it's address. The & in front of the variable name, means "the address of"the variable:
my_variable = a value
&my_variable = an address
Code:
my_gcd_function(number1, number2, &myNumerator, &myDenominator);
Would call a function, and pass two numbers (1 and 2) that could be changed, but the change will not have any effect after the function ends, and two addresses to numbers that, once changed in the function, will remain changed when the function ends.
Making your gcd function first line, (definition), to look like:
Code:
void my_gcd_function(int number1, int number2, *myNumerator, *myDenominator) {
//add your gcd code here
}
And Welcome to the forum, Kerniga! :D
If you could post your code, with some example numbers, we can be much more specific.
-
Thanks for the warm welcome! This is my code so far:
#include <stdio.h>
int gcd(int a, int b);
int main(void)
{
int num, den;
printf("Please enter a numerator and denominator: ");
scanf("%d%d\n", &num, &den);
printf("Simplified fraction: %d %d", );
return 0;
}
int gcd(int a, int b)
{
int rem;
if((rem = a % b) == 0) {
return b;
}
else {
return gcd(b, rem);
}
}
-
sorry, I think I was supposed to use this!:
Code:
#include <stdio.h>
int gcd(int a, int b);
int main(void)
{
int num, den;
printf("Please enter two integers: ");
scanf("%d%d\n", &num, &den);
printf("Simplified fraction: ");
return 0;
}
int gcd(int a, int b)
{
int rem;
if((rem = a % b) == 0) {
return b;
}
else {
return gcd(b, rem);
}
}
-
So in main you just need to invoke gcd with the parameters you have input-ed via scanf.
Code:
printf("%d",gcd(num,den));
However, first you want to verify that you are taking input correctly.
Then, test your program to see if your gcd function works correctly with different values.
Then, you are ready to print your simplified function, which I am assuming is obtained as follows:
Code:
int my_gcd = gcd(num,den);
int simple_num = num / my_gcd;
int simple_den = den / my_gcd;
printf("%d / %d",simple_num,simple_den);
-
Done it, and it works!! Thanks so much!
-
Good job, glad to be of help.