Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/130.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 递归计算满足条件的值的数量并返回该数量_C++_Recursion - Fatal编程技术网

C++ 递归计算满足条件的值的数量并返回该数量

C++ 递归计算满足条件的值的数量并返回该数量,c++,recursion,C++,Recursion,我需要计算a和b(本例中为2和9)之间有多少个值立方体以2和5之间的数字结尾。一切都必须用递归来完成 这段代码的输出是 c部分=recc=4 32767 0 这对我来说毫无意义。它正确地计算了n的值,但一旦要求返回n,就会返回0或32767,就好像它没有定义一样 有人能指出这个问题吗 #include <iostream> #include <string> using namespace std; void partb(int a, int b){ if(a&l

我需要计算a和b(本例中为2和9)之间有多少个值立方体以2和5之间的数字结尾。一切都必须用递归来完成

这段代码的输出是

c部分=recc=4 32767 0

这对我来说毫无意义。它正确地计算了n的值,但一旦要求返回n,就会返回0或32767,就好像它没有定义一样

有人能指出这个问题吗

#include <iostream>
#include <string>
using namespace std;
void partb(int a, int b){
    if(a<=b){
        int p = (a*a*a)%10;
    else if(p>=2 && p<=5){
        cout<<a*a*a<<" ";
      }
    partb(a+1, b);
    }
}
int recc(int n, int a, int b){
    int p = (a*a*a)%10;
    if(a>b){
        cout<<"recc = " << n << endl;
        return n;
    }
    else if(a<=b){
        if(p>=2 && p<=5){
            n++;
        }
        recc(n, a+1, b);
    }
}
int partc(int a, int b){
    int n = recc(0, a, b);
    cout<<endl<< "part c = " << recc(0, a, b) << endl;
    return n;
}
int main(){
    int n=partc(2,9);
    cout << n << endl;
    return 0;
}
#包括
#包括
使用名称空间std;
无效部分b(内部a、内部b){

如果函数中的(a=2&&p不是所有控制路径都返回值,那么在使用返回值时,您会得到未定义的行为

现在,函数本身不必要地复杂这一事实无助于实现这一点。让我们重写它,以使用递归的常规做法:

int recc(int a, int b)
{
    if (a > b) return 0;
    int p = (a*a*a)%10;
    int n = (p>=2 && p<=5) ? 1 : 0;
    return n + recc(a+1, b);
}

如果(p>=2&&pGood spotting),OP在
partb
中的代码中可能存在的重复应该也是另一个问题。我甚至没有阅读该函数,因为它没有在任何地方使用。
int partc(int a, int b)
{
    int n = recc(a, b);
    cout << endl << "part c = " << n << endl;
    return n;
}