recursive divison of number
I have following code to divide one number recursively by another number:
#include <iostream>
using namespace std;
int divide(int number,int dividend){
int answer=0;
if (number>dividend || number==dividend ){
answer+=1;
return divide(number-dividend,dividend);
}
return answer;
}
int main(){
cout<<divide(20,5)<<en开发者_JAVA百科dl;
return 0;
}
but unfortunately I get zero as answer. Do you see what is wrong?
Answer is a local variable. When you run this code, the first call to divide
creates an instance of the answer
variable, sets it to 0, and then increments it to 1. Then, when you recursively call divide
again, it creates a brand new instance of the answer
variable, sets that instance to 0, and then increments that instance to 1.
In your final call to divide
, it creates a brand new instance of the answer
variable, sets that instance to 0, but since now number<=dividend
it doesn't increment it, and it returns that instance of answer
which is 0.
In the if
branch you are incrementing answer
but returning something unrelated (the result of the recursive call). I am sure, this is not what you want. Go from there.
You are recursively running the following code:
if (number>dividend || number==dividend ){
answer+=1;
return divide(number-dividend,dividend);
}
But once the recursive calling ends (which is number < dividend
), you will ignore the if statement and return 0;
You do int answer=0;
in the start of function call, so when the if
statement is wrong, it returns 0
so you should define it as input parameter (by reference call) or make it global (not recommended) and do not set it to zero, just set it before your recursive function call.
精彩评论