[英]How can I make sure that the recursion terminates?
In this Example the function terminates in a strange way, although the values don't change (no base case is reached)在这个例子中,function 以一种奇怪的方式终止,尽管值没有改变(没有达到基本情况)
#include<stdio.h>
int power(int a, int b);
int main(){
int a;
int b;
printf(" Enter number: ");
scanf(" %d",&a);
printf(" Enter it's power: ");
scanf( " %d",&b);
printf("\n\n Result: %d",power(a,b));
}
int power(int a, int b){
if( b == 0)
return 1;
if ( a == 0)
return 0;
if ( b == 1)
return a;
else return a*(b,a); //shouldn't it be: "else return a*(a,b-1);" , how does this work!
}
This function is actually not recursive since it's not calling itself:这个 function 实际上不是递归的,因为它没有调用自己:
else return a*(b,a);
All it's doing is returning a*a
.它所做的只是返回
a*a
。 It should be:它应该是:
else return a*power(a,b-1);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.