C++求最大公约最小公倍数以下代码运行被终止,请问问题出在哪里?

#include
int main(){
int a,b,temp,s1,s2,z;
scanf("%d %d",&a,&b);
if(a<b){
temp=a;
a=b;
b=temp;
}
s1=a;
s2=b;
while(b!=0){
temp=s1%s2;
s1=s2;
s2=temp;
}
z=a*b/s2;
printf("%d %d",s2,z);
}

#include //要包含头文件
int main(){
int a,b,temp,s1,s2,z;
scanf("%d %d",&a,&b);
if(a<b){
temp=a;
a=b;
b=temp;
}
s1=a;
s2=b;
while(s2!=0){ //b改为s2,不然死循环
temp=s1%s2;
s1=s2;
s2=temp;
}
z=a*b/s2; //退出循环时,s2为0,除零错误
printf("%d %d",s2,s1); //s1即为最大公约数
return 0; //要有返回值
}

你的循环条件b!=0一直满足,会死循环
要在while里加入b的变换
或者不要这样写循环条件

while(b!=0){
temp=s1%s2;
s1=s2;
s2=temp;
}
你循环里的代码并没有修改b,所以这是死循环。

while(temp!=0){
s1=s2;
s2=temp;
temp=s1%s2;
}

1 循环终止条件不对,无法退出循环。
2 求最小公倍数时,分母不应该是s2,否则发生除零错误。

修改后的代码如下:

#include "stdio.h"
main()
{
    int a, b, num1, num2, temp, c;
    printf("please input two numbers:\n");
    scanf("%d %d", &num1, &num2);
    if (num1 < num2)
    {
        temp = num1;
        num1 = num2;
        num2 = temp;
    }
    a = num1; b = num2;
    while (b != 0)/*利用辗除法,直到b为0为止*/
    {
        temp = a%b;
        a = b;
        b = temp;
    }

    c = num1*num2 / a;
    printf("最大公约数:%d\n", a);
    printf("最小公倍数: %d\n", c);
}

测试结果如下图:

图片说明

用心回答每个问题,如果有帮助,请采纳答案好吗,非常感谢~~~

while(b!=0){
temp=s1%s2;
s1=s2;
s2=temp;
}死循环