使用结构和递归查找整数数组中的最大数字
Use struct and recursion to find the largest number in an integer array
我需要使用递归来查找整数数组中的最大数字。另外,我需要获取最大数字的值和索引。我使用了"结构",但它给了我一些奇怪的数字,我不知道为什么。
这是我的结构:
struct maxNumber
{
int index;
int value;
};
这是我的find_largest函数:
maxNumber Numbers::find_largest()
{
maxNumber max;
int current ;//keep track of the current counter
if(size == 1)
{
max.value = numArray[0];
max.index = 0;
return max;
}
if(current < size && size != 0) //loop through all numbers in the array
{
if(numArray[current] >= max.value)
{
max.value = numArray[current];
max.index = current;
}
current++;
find_largest();
}
return max;
}
然后,在主函数中,我只是这样做:
int result = num.find_largest().value;
cout << "The largest number is " << result << endl;
但是,它给了我一个非常大的数字。需要一些帮助来找出问题所在。
您的主要问题是current
具有本地存储,因此在每次调用findLargest
时都会重新分配。 将声明更改为此声明
static int current = 0;
如果在类定义中的其他地方正确定义了size
和numArray
,它应该可以工作。
但是同样的事情在max
上更微妙地发生,它也应该静态声明。
刚刚修复了这个问题。问题正如@stvcisco所说:我没有在函数中传递参数,所以它只是一次又一次地调用函数。这是固定代码。
maxNumber Numbers::find_largest(maxNumber max, int size)
{
if(size == 1)
{
max.value = numArray[0];
max.index = 0;
}
if( size > 1) //loop through all numbers in the array
{
if(numArray[size-1] >= max.value)
{
max.value = numArray[size-1];
max.index = size-1;
return max = find_largest(max, size-1);
}
//return max = find_largest(max, size-1);
else
{
size--;
find_largest(max,size);
}
}
return max;
}
相关文章:
- 在将数字随机生成为数组期间从内存输出随机数的数组
- 如何计算数组中元素的位数?(不是数组的长度),并计算其数字的总和
- 数组/c++中的大量数字
- 遍历并行数组以确定C++中的最大数字
- 整数区间(或 int 数组)中每个数字的出现次数
- 如何在 C++ 中将文件中的逗号分隔数字读取到数组中?
- 将随机生成的数字添加到数组 + 对这些数组求平均值
- 遇到此问题时遇到困难:允许用户输入数组的值并使用 for,而循环也输出输入的最大数字
- 获取 2D 数组 c++ 中的所有数字对
- 为什么使用数组元素查找最大数字的程序不起作用?
- 如何从向量或数组中选择最常见的数字?(前五名)C++
- 如何从保存在 Java 中C++的字节数组中读取数字?
- 以十为基数的数字到布尔数组,该数组要求二进制/基数为 2 的数字
- C++ 检查结果数组中有多少次数字
- 如何在不使用 C++ 中的数组或函数的情况下查找 N 位数字的所有排列
- 如何在C++中有效地将数字值重新分配给字符数组
- 查找数组中的最小数字
- 查找数组中重复(重复)数字的索引
- 我必须找到给定数组中所有数字的周期,就像有很多解决方案,但数组的大小是 10^5
- 类、数字/数组或对象中的对象