繁体   English   中英

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

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

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

#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数量。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM