使用递归的C 在向量中找到非齐射的数量

C++ using recursion find the number of nonzeros in a Vector

本文关键字:递归 向量      更新时间:2023-10-16

编辑我有此代码可以与数组一起使用,但是我无法将其与向量一起使用,有人知道我如何将其从使用数组更改为矢量?

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)永远不会退出,因为您不修改 is

您实际上可以使函数更简单,首先是没有循环(这就是递归的目的),然后意识到您只需要大小和当前索引作为参数。那你可以像

一样
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,而 true1false0。然后,它添加了下一个索引的返回值,该索引通过使用递归调用来获取。

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));
    }
}