使用递归的C 在向量中找到非齐射的数量
C++ using recursion find the number of nonzeros in a Vector
编辑我有此代码可以与数组一起使用,但是我无法将其与向量一起使用,有人知道我如何将其从使用数组更改为矢量?
?int count(double* arr, int length);
int main()
{
double arr[10] = {0.0, 1.3, 2.5, 11.34, 0.0, 9.8, 6.4, 0.0, 4.3, 0.0};
cout << "There are " << count(arr, 10) << " nonzeros in this array!nn";
return 0;
}
int count(double* arr, int length)
{
if (!length)
{
return 0;
}
int c = count(arr+1, length-1);
return arr[0] != 0.0 ? c + 1 : c;
}
您循环while (i < s)
永远不会退出,因为您不修改 i
或 s
。
您实际上可以使函数更简单,首先是没有循环(这就是递归的目的),然后意识到您只需要大小和当前索引作为参数。那你可以像
一样int nonzeroes(double* digits, size_t size, size_t index)
{
if (index < size)
{
return (digits[index] != 0.0) + nonzeroes(digits, size, index + 1);
}
return 0;
}
这起作用是因为布尔值可以隐式转换为 int
,而 true
为 1
, false
为 0
。然后,它添加了下一个索引的返回值,该索引通过使用递归调用来获取。
main
功能的初始调用应该像
nonzeroes(digits, s, 0)
使用索引零开始计数。
我建议您在输入递归电话以查看其工作原理时使用debugger逐线逐步浏览代码。
在旁注上,如果您想要C 中的动态数组,则应使用std::vector
。
在另一个旁注上,对于像 0.0
相比的简单情况,如果您通过其他算法或算术创建值,则会有复合的舍入错误,这意味着该值可能是 close ,但不完全等于零。这可以通过使用 epsilon 值来解决,例如使用std::numeric_limits<double>::epsilon
。
我可能是错误的,但是要使用递归,您需要一个基本情况,以停止呼叫,我认为您不需要通过计数。
我认为一个选择可能是:
int nonzeros(double digits[], int s, int i)
{
if (i == s)
{
return 0;
}
else if (digits[i] != 0.0)
{
return (1 + nonzeros(digits, s, i + 1));
}
else
{
return (nonzeros(digits, s, i + 1));
}
}
相关文章:
- 以C++递归方式查找向量中的最大值
- 尾递归,带有通过引用传递的向量
- 返回向量 C++ 上的递归
- 递归回文检查,不使用向量、大小或其他参数
- n维向量的递归可变参数模板函数
- 在不使用递归的情况下求解所有 2D 字符串向量组合?(C++)
- 使用迭代器对向量的C 递归初始化产生不一致的结果
- 我们应该全局声明一个向量还是在递归函数中传递它以减少内存使用
- 递归向量中的最小正数
- 使用递归C++向量元素的总和
- 如何在递归函数中打印向量
- 递归结构的向量有内存问题
- 递归函数,返回向量中所有元素的总和
- 使用递归的C 在向量中找到非齐射的数量
- boost::variant:具有递归向量类型的奇怪行为
- 在递归函数中收集cout或输出为向量
- 从向量中删除重复项,递归 c++
- 使用递归将元素添加到向量中
- 迭代和递归地查找向量中是否存在元素
- 递归对向量进行排序的最简单方法