简体   繁体   English

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

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

I don't know how to make this code to work for more than two numbers. 我不知道如何使这个代码适用于两个以上的数字。 It works perfectly for two numbers. 它适用于两个数字。

#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;
}

For example if we input 6 and 12 the code says 6 which is right. 例如,如果我们输入6和12,则代码表示6是正确的。

Just turn your calculation into a function: 只需将计算转换为函数:

#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;
}

Now you can easily calculate HCF for as many numbers as you want. 现在,您可以根据需要轻松计算HCF数量。

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

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