C++多种功能

Multiple functions in C++

本文关键字:功能 C++      更新时间:2023-10-16

今天我试图用多个函数做递归,我正在使用一些函数,因为我正在使用一个在其下方声明的函数

这是我的代码:

#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)函数,因此无法执行任何操作

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

多谢。

因此,您看到的问题是在您使用函数后定义的,因此编译器看不到它。这个"问题"是通过函数的声明来解决的,然后定义它。在您的情况下,您可以声明 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 位/标准dc++.h

你需要添加一个函数 h 的前向声明才能编译你的代码,如下所示:

#define MOD 10
int f(int x){
if(x == 4) return 1;
return 3*f(((2*x+2)%11)-1);
}
int h(int); // add this line and you will be alright! ;)
int q(int x){
if(x == 7) return 1;
return f(x) + q((3*x)%MOD);
}
...

通常,您可以在此处找到为什么需要这样做。

首先声明你的函数。

#include<bits/stdc++.h>
#define MOD 10
// declaring your functions here makes sure that you can
// use them before they are fully defined.
int f(int x);
int q(int x);
int g(int x);
int h(int x);
// Now here below you can use the functions declared above
// at any place you wish.
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() {
std::cout << g(4);
return 0;
}