[英]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.