编辑 我得到了这段代码来处理数组,但我无法让它处理 vector ,有谁知道我如何将它从使用数组更改为 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!\n\n";
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;
}
这是有效的,因为 bool 值可以隐式转换为 int
, 与 true
正在1
和 false
正在0
.然后添加使用递归调用获取的下一个索引的返回值。
来自您的 main
的初始调用功能应该是这样的
nonzeroes(digits, s, 0)
使用索引零开始计数。
我建议您使用调试器逐行调试代码,同时输入递归调用以查看其工作原理。
附带说明一下,如果你想要 C++ 中的动态数组,你应该使用 std::vector
.
另一方面,对于像你这样的简单案例,与 0.0
进行比较会起作用,但如果您通过其他算法或算术创建值,则会出现复合舍入误差,这意味着该值可能接近但不完全等于零。这可以通过使用 epsilon 值来解决,例如使用 std::numeric_limits<double>::epsilon
.
关于C++使用递归查找Vector中非零的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30064678/