为什么它没有向我展示最大的共同点?

Why it doesn't show me the greatest common divison?

本文关键字:共同点 为什么      更新时间:2023-10-16

当我尝试启动程序时,它不起作用并且没有显示任何错误。为什么?

#include <iostream>
using namespace std;
int main()
{
    unsigned a,b;
    cout<<"a=";
    cin>>a;
    cout<<"b=";
    cin>>b;
    {
        while(a!=b)
        {
            if(a>b)
                (a==a-b);
            else
                (b==b-a);
        }
    }
    cout<<"cmmdc=",a;
    return 0;
}

a==a-b替换为 a=a-b

b==b-a替换为 b=b-a

运算符==是比较,它不会修改其参数。运算符=赋值,它将左参数修改为其右参数的值。

cout<<"cmmdc=",a替换为 cout<<"cmmdc="<<a ,否则不会打印a

即使在将

== s 更改为 = s 之后,如果 a 中的任何一个(但不是两个)b 都是 0,你也会得到一个无限循环。若要避免这种情况,请改用此循环:

while (b != 0) {
  const unsigned olda = a;
  a = b;
  b = olda % b;
}
// GCD is now in a.

这是找到两个数字的 gcd 的最简单方法:

#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
    int a,b;
    cout<<"a = ";
    cin>>a;
    cout<<"b = ";
    cin>>b;
    cout<<"GCD = " << __gcd(a,b);
}