递归中 void 的无效操作数

invalid operands of void in recursion

我正在尝试使用递归将数字拆分,例如 123 拆分为 12,3。所以我遇到了问题,因为我使用了 void,现在编译器显示:

invalid operands of types 'void' and 'int' to binary 'operator !='

递归所在的最后一行。 我假设它是关于 ab 一开始的比较但是 abint 类型所以我不明白为什么我不能比较他们 zero.

void podzial ( int N, int a, int b, int & k )
{
if(N==0 and a!=0 and b!=0)
    if(prime(a,b))
    {
        cout<<a<<b<<endl;
        k++;
    }
else if(N==0) return;
else
{
    a*=10; b*=10;
    podzial(N/10,a+(N%10),b,k) or podzial(N/10,a,b+(N%10),k);
}
}

podzial 具有 void return 值,因此不能用作 or(即 ||)条件检查中的参数.

您不希望函数 return 和 int 吗?

还要记住 or 是短路的,因此如果左侧的计算结果为 true,则不会对右侧进行计算。

void podzial (int N, int a, int b, int& k) {
    ...
    else if(N == 0) {
        return;   // Should't have a return here since podzial's return type is void.
                  // 
                  // You can just do what I do in the code example below.
    }
    ...

您可能想要重新组织您的 if 语句...

void podzial (int N, int a, int b, int& k) {
    if(N == 0) {
        if(a != 0 && b != 0) {
            if(prime(a, b)) {
                cout << a << b << endl;
                k++;
            }
        }
        cout << "Recursion terminated";
    }
    else {
        a *= 10; 
        b *= 10;
        podzial( N / 10, a + (N % 10), b, k)
        // or podzial(N / 10, a, b + (N % 10), k);
        // If you actually wanted to write...
        // return podzial(...) || podzial(....)
        // Then you'll need to add a return type to the function header
        // and can keep the 'else if(N==0) return 0;'
    }
}

对于 void return 类型,如果你不想进一步递归,请确保你的终止子句是唯一在最后一次迭代中运行的东西(一个巨大的 if/else声明)。