I am having trouble returning the correct value of the GCD of two integers.
The number returned is always 20k+ which obviously is not correct when I am using numbers like 5 and 10.
Does anybody know what the problem is with my code?
#include <stdio.h>
#include "stdafx.h"
#include <stdlib.h>
int gcd(int x, int y);
int main(void)
{
int one, two;
printf("This program finds the Greatest Common Divisor of two numbers.\n");
printf("Enter the first number: ");
scanf("%d", &one);
printf("\n");
printf("Enter the second number: ");
scanf("%d", &two);
gcd(one, two);
printf("The Greatest Common Divider is %d\n", &one);
return 0;
}
int gcd(int x, int y)
{
int z;
x = abs(x);
y = abs(y);
while (y > 0)
{
z = y;
y = x % y;
x = z;
}
return x;
}
1) you're returning the result from gcd, but you're not putting that result in any variable. Line 18 should look like this:
one = gcd(one,two);
2) you're printing the address of your 'one' variable rather than the contents of the variable. See line 19. &one is a pointer to 'one', it is not the value of 'one'. Remove the & symbol.
// Greatest_Common_Divisor_Antonson.cpp : Defines the entry point for the console application.
//
#include <stdio.h>
#include "stdafx.h"
#include <stdlib.h>
int gcd(int x, int y);
int main(void)
{
int one, two, grt_com_div;
printf("This program finds the Greatest Common Divisor of two numbers.\n");
printf("Enter the first number: ");
scanf("%d", &one);
printf("\n");
printf("Enter the second number: ");
scanf("%d", &two);
grt_com_div = gcd(one,two);
printf("The Greatest Common Divisor is %d\n", grt_com_div);
return 0;
}
int gcd(int x, int y)
{
int z;
x = abs(x);
y = abs(y);
while (y > 0)
{
z = y;
y = x % y;
x = z;
}
return x;
}
hehe your gcd function is much better than mine! gonna use yours :) (when I wrote mine I wasn't aware there was the % operator in c++ lol... also this is the first time when I see using the variables passed to the function makes sense :)