[英]GCD - always returns 1
如果有人可以查看我的代碼並向我解釋為什么最大公約數總是返回為 1,我將不勝感激。我正在使用歐幾里德算法來查找 gcd。
#include <iostream>
using namespace std;
int gcd(int a, int b)
{
while (b)
{
int tmp = b;
b = a % b;
a = tmp;
}
return a;
}
int main()
{
cout << "Enter first integer: ";
int a;
cin >> a;
cout << "Enter second integer: ";
int b;
cin >> b;
int gcd(int a, int b);
cout << "The greatest common divisor is: " << gcd << endl;
return 0;
}
您對 function 的調用不正確。 You are trying to redefine a function inside a function which is not possible, To declear a function inside a function use lamda functions
. 您可以在cout statement
中調用 function,就像我在下面的代碼中所做的那樣。
注意: using namespace std
永遠不會被認為是一種好的做法,盡量避免使用它。
快樂編碼。
#include <iostream>
int gcd(int a, int b) {
while (b) {
int tmp = b;
b = a % b;
a = tmp;
}
return a;
}
int main() {
std::cout << "Enter first integer: ";
int a;
std::cin >> a;
std::cout << "Enter second integer: ";
int b;
std::cin >> b;
std::cout << "The greatest common divisor is: " << gcd(a, b) << "\n";
return 0;
}
您沒有將 GCD 存儲為變量。 你應該這樣做:
int gcdCalc = gcd(a, b);
cout << "The greatest common divisor is: " << gcdCalc << endl;
此外,由於大多數數字互為質數,因此 GCD 很多時候都是 1。 用 48 和 2 試試,你應該得到 GCD 為 2。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.