在 C++ 中查找 2 个数字的 GCD
find gcd of 2 numbers in 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*
转换为整数
- 使用
atoi()
方法 ==> 阅读此内容 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;
}
相关文章:
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- 检查输入是否不是整数或数字
- 如何(从固定列表中)选择一个数字序列,该序列将与目标数字相加
- 如何用数字处理log(0)
- 最高有效数字侧的第N位
- 如何获取一个数字的前3位
- 查找最接近的大于当前数字的数字的索引
- 找到两对数字,使它们的乘积的绝对差最小化
- 我想做一个彼此不同但重复出现的数字
- 将数字转换为字母(例如:123 转换为一二三)
- C++如何计算用户输入的数字中的偶数位数
- 如何在C++中确定文本文件中的元素是字符还是数字
- 打印数字图案
- C++问题:用户认为数字1-100,程序提出问题不超过6次即可得到答案。无法正确
- 如何检查一个c++字符串中有多少相同的字符/数字
- 在 C++ 中查找 2 个数字的 GCD
- 数字混淆的GCD
- 求一组数字的GCD
- 查找具有给定GCD值的数字