如何将此代码转换为两个以上的数字(计算HCF)

How to transform this code to work for more than two numbers (calculating HCF)

本文关键字:两个 HCF 计算 数字 代码 转换      更新时间:2023-10-16

我不知道如何使此代码以两个以上的数字工作。它适用于两个数字。

#include <iostream>
using namespace std;
int main() {
    int n1, n2;
    cout << "   Insert 2 numbers: ";
    cin >> n1 >> n2;
    while(n1 != n2)
    {
        if(n1 > n2)
        {
            n1 -= n2;
        }
        else
        {
            n2 -= n1;
        }
    }
i   cout << "HCF = " << n1; return 0;
}

例如,如果我们输入6和12,则代码为6,这是正确的。

只需将您的计算变成一个函数:

#include <iostream>
int hcf(int n1, int n2);
int main() {
    int n1, n2, n3;
    std::cout << "   Insert 3 numbers: ";
    std::cin >> n1 >> n2 >> n3;
    std::cout << "HCF = " << hcf(n1, hcf(n2, n3));
    return 0;
}
int hcf(int n1, int n2) {
    while (n1 != n2) {
        if (n1 > n2)
            n1 -= n2;
        else
            n2 -= n1;
    }
    return n1;
}

现在,您可以根据需要的数字轻松计算HCF。