[英]problem with returning from function in c++/c
i have this problem with returning from function. 我从功能返回有这个问题。 it's a search function, it should return 1 if the function find the value that i give but No, it's returning the 0 instead of 1. (sorry for my bad english.)
这是一个搜索功能,如果该功能找到我给出的值,但应该返回1,但不,它将返回0而不是1。(对不起,我的英语不好。)
int rech(int tab[],int n,int i,int r){
if(i<n){
if(tab[i]==r){
return 1;
}
i++;
rech(tab,n,i,r);
}
return 0;
}
int main(int argc, char** argv) {
int tab[5]={1,2,3,4,5};
printf("%d",rech(tab,5,0,2));
return 0;
}
When you use return
you will return to the caller, which in a recursive function will mean the same function most of the times. 当您使用
return
您将返回到调用方,这在递归函数中通常表示相同的函数。
Change 更改
rech(tab,n,i,r);
to 至
return rech(tab,n,i,r);
Let's walk through it together. 让我们一起经历一下。
When rech gets called the first time: 第一次调用rech时:
First time we call rech: rech(tab = {1,2,3,4,5}, n = 5, i = 0, r = 2)
is i < n
or 0 < 5
? 第一次调用rech:
rech(tab = {1,2,3,4,5}, n = 5, i = 0, r = 2)
是i < n
还是0 < 5
? This is true. 这是真的。 Now we check if
tab[i] == r
or 1 == 2
. 现在我们检查
tab[i] == r
还是1 == 2
。 This is false. 这是错误的。 We increase i and start over again
我们增加我并重新开始
Second time we call rech: rech(tab = {1,2,3,4,5}, n = 5, i = 1, r = 2)
is tab[i] < r
or 1 < 5
? 第二次调用rech:
rech(tab = {1,2,3,4,5}, n = 5, i = 1, r = 2)
是tab[i] < r
或1 < 5
吗? This is true. 这是真的。 Now we check if
tab[i] == r
or 2 == 2
. 现在我们检查
tab[i] == r
或2 == 2
。 This is true. 这是真的。 We return 1 back to the first time rech got called.
我们将1返回到第一次调用rech。
Back to the first time we call rech: rech(tab, n, i, r)
returned 1. So, in coding terms this would look like 1;
回到第一次调用rech:
rech(tab, n, i, r)
返回1。因此,在编码方面,它看起来像1;
which does nothing. 什么都不做。
Now we are done with the if statement and return 0 to main. 现在,我们完成了if语句,并向main返回0。
main now prints out a 0 and the program ends. main现在输出0,程序结束。
This is the process of debugging the code. 这是调试代码的过程。
To have the program return the 1 back to main instead you'll want to have it return the rech function because otherwise, the recursive call does nothing. 要使程序将1返回到main,则需要使其返回rech函数,因为否则,递归调用将不执行任何操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.