在 C++ 中查找 2 个数字的 GCD

  • 本文关键字:数字 GCD C++ 查找 c++
  • 更新时间 :
  • 英文 :


这是我的程序

#include <bits/stdc++.h> 
using namespace std; 
// Function to return gcd of a and b 
int gcd(int a, int b) 
{ 
if (a == 0) 
return b; 
return gcd(b % a, a); 
} 
// Function to find gcd of input2ay of 
// numbers 
int findGCD(int input2[], int n) 
{ 
int result = input2[0]; 
for (int i = 1; i < n; i++) 
{ 
result = gcd(input2[i], result); 
if(result == 1) 
{ 
return 1; 
} 
} 
return result; 
} 
// Driver code 
int main(int input1,int input2[40]) 
{ 
int n = sizeof(input2) / sizeof(input2[0]); 
cout << findGCD(input2, n) << endl; 
return 0; 
} 

输入必须采用以下格式 3 2 4
8,
其中 3 是数组的大小,2 4 8 是数组的元素。
现在我收到以下错误

main.cpp:40:5: warning: second argument of ‘int main(int, int*)’ should be ‘char **’ [-Wmain]
int main(int input1,int input2[40])
^~~~
main.cpp: In function ‘int main(int, int*)’:
main.cpp:43:23: warning: ‘sizeof’ on array function parameter ‘input2’ will return size of ‘int*’ [-Wsizeof-array-argument]
int n = sizeof(input2) / sizeof(input2[0]);
^
main.cpp:40:34: note: declared here
int main(int input1,int input2[40])
^

这里有什么问题?
我的问题主要是添加更多详细信息的代码。

根据我使用 atoi 提出的建议进行编辑

#include <stdio.h>
unsigned gcd(unsigned x, unsigned y){
unsigned wk;
if(x<y){ wk=x;x=y;y=wk; }
while(y){
wk = x%y;
x=y;
y=wk;
}
return x;
}
int gcd_a(int n, int a[n]){
if(n==1) return a[0];
if(n==2) return gcd(a[0], a[1]);
int h = n / 2;
return gcd(gcd_a(h, &a[0]), gcd_a(n - h, &a[h]));
}
int main(int argc ,char *argv[]){
// argc is number of arguments given including a.out in command line
// argv is a list of string containing command line arguments
int total = 0;
int i,input1;
int *value;
for(i = 1; i < argc; i++)
{
// The integers given is read as (char *)
value[i] = atoi(argv[i]);
total++;
}

input1 = total;
int gcd = gcd_a(input1, value);
printf("%dn", gcd);
return 0;
}

但这仍然没有给我想要的结果。 我在网上编译了它,但它没有给出任何错误,但它也没有采取任何论据。

该帖子无法提交,因为它看起来主要是SO中的代码java脚本编程错误。

主方法声明必须int main(int ,char**);
在这里,您将获得 c 字符串数组。 即(["10","20","40"....]).
所以你需要使用以下方法将char*转换为整数

  1. 使用atoi()方法 ==> 阅读此内容
  2. sscanf()方法 ==> 阅读此内容

请参阅以下代码

int findGCD(char* input2[], int n) 
{ 
int result = atoi(input2[1]); /*Here first argument is fileName itself ,so we are taking from second.i.e input2[1]*/
for (int i = 2; i < n; i++) 
{ 
int a = atoi(input2[i]);
result = gcd(a, result); 
if(result == 1) 
{ 
return 1; 
} 
} 
return result; 
} 
// Driver code 
int main(int args,char** argv) 
{ 
// for(int i = 0;i < args;i++)
// {
//     cout <<"argv["<<i<<"] = "<<argv[i]<<endl;
// }
cout << "GCD::"<<findGCD(argv, args) << endl; 
return 0;
} 

最新更新