2

在尝试从简化的编程中执行 GCD 和 LCM 程序时……我遇到了结果问题。我做的一切都是正确的(根据我),甚至逐字检查,但问题仍然存在......我只粘贴正常方法的代码。

#include <stdio.h>

int main()
{
    int a, b, x, y, t, gcd, lcm;
  
    printf("Enter first number :");
    scanf("%d", &a);
    printf("Enter first number :");
    scanf("%d", &b);
  
    a = x;
    b = y;
  
    while (b != 0)
    {
        t = b;
        b = a % b;
        a = t;
    }
  
    gcd = a;
    lcm = (x * y)/gcd;
  
    printf("Greatest common divisior of %d and %d = %d\n", x, y, gcd);
    printf("Lowest common divisior of %d and %d = %d\n", x, y, lcm);
  
    getch();    
}
4

3 回答 3

3

至少这部分是根本错误的:

int a, b, x, y, t, gcd, lcm;

printf("Enter first number :");
scanf("%d", &a);
printf("Enter first number :");
scanf("%d", &b);

a = x;
b = y;

因此,您正在声明xy未初始化,然后将它们分配给- 现在a并且不包含用户输入的值,而是一些垃圾。你可能想要bab

x = a;
y = b;

反而。

于 2012-12-17T23:52:13.887 回答
0

最好试试这个。这更容易运行。

#include<stdio.h>
int GCD(int,int); 
void main(){
int p,q;
printf("Enter the two numbers: ");
scanf("%d %d",&p,&q);
printf("\nThe GCD is %d",GCD(p,q));
printf("\nThe LCM is %d",(p*q)/(GCD(p,q)));
}
int GCD(int x,int y){
if(x<y)
GCD(y,x);
if(x%y==0)
return y;
else{
GCD(y,x%y);
 }
}
于 2014-03-21T10:57:26.190 回答
0

尝试一下

#include<stdio.h>
int main(){
int a,b,lcm,gcd;
printf("enter two value:\n");
scanf("%d%d",&a,&b);
gcd=GCD(a,b);
lcm=LCM(a,b);
printf("LCM=%d and GCD=%d",lcm,gcd);
return 0;
}
int GCD(int a, int b){

while(a!=b){
    if(a>b){
        a=a-b;
    }else{
    b=b-a;
    }
    }
  return a;
}
int LCM(int a, int b){
return (a*b)/GCD(a,b);
}
于 2017-07-06T15:36:25.317 回答