首页 > 解决方案 > C++ 中的多个函数

问题描述

今天我试图用多个函数进行递归,我正在使用一些函数,因为我正在使用一个在它下面声明的函数

这是我的代码:

#include<bits/stdc++.h>
using namespace std;
#define MOD 10

int f(int x){
    if(x == 4) return 1;
    return 3*f(((2*x+2)%11)-1);
}


int q(int x){
    if(x == 7) return 1;
    return f(x) + q((3*x)%MOD);
}

int g(int x){
    if(x == 0) return 1;
    return (g(x-1)+f(g(x-1)) + f(x-1) + h(x-1))%MOD;
}

int h(int x){
    if(x == 0) return 1;
    return (2*h(x-1) + g(x-1) + q(f(x-1)%10))%MOD;
}


int main() {

    cout << g(4);

    return 0;
}

错误是在函数g(x)中,它正在访问h(x)下面声明的函数,并且h(x)函数正在使用g(x)函数,因此无法执行任何操作

请让我知道我应该怎么做才能完成这项工作。

非常感谢。

标签: c++function

解决方案


所以你看到一个函数是在你使用它之后定义的,所以你的编译器看不到它。这个“问题”通过函数的声明来解决,然后再定义它。在您的情况下,您可以在 main 之上声明所有函数,然后在 main 之后定义(实现它):

#include <iostream>
using namespace std;
#define MOD 10

// declaration ***
int f(int x);
int q(int x);
int g(int x);
int h(int x);
// **************

// main ***
int main() {

    cout << g(4);

    return 0;
}
// **************

// definition ***
int f(int x){
    if(x == 4) return 1;
    return 3*f(((2*x+2)%11)-1);
}

int q(int x){
    if(x == 7) return 1;
    return f(x) + q((3*x)%MOD);
}

int g(int x){
    if(x == 0) return 1;
    return (g(x-1)+f(g(x-1)) + f(x-1) + h(x-1))%MOD;
}

int h(int x){
    if(x == 0) return 1;
    return (2*h(x-1) + g(x-1) + q(f(x-1)%10))%MOD;
}
// **************

也不包括#include bits/stdc++.h


推荐阅读