You can try this, it should work:
int dividebytwo (int a){
static int answer = 0;
if (a < 0){
if ((answer * 2) > a){
answer --;
return dividebytwo (a);
}
return answer;
} else if (a > 0){
if ((answer * 2) < a){
answer ++;
return dividebytwo (a);
}
return answer;
}
return 0;
}
The trick here is using the static
attribute. The static attribute means that the variable is only initialized once and retains its value after every function call. Really, you're using two parameters but it looks like you're only using one.
The only downside to this function is that you can only count on it to work more than once. Since this is probably for a simple homework assignment, it probably doesn't matter. But in reality, this is considered hugely inefficient and unreliable.
To compensate for the only-works-once
factor, may add one of these fixes:
declare
answer
as a global variable and set it to0
before every function call.append
return answer = 0;
to the end of the function, instead ofreturn 0;
. This is so that whenever you want to call it again, you would call it beforehand asdividebytwo (0);
.
I also cannot stress enough how weird of a concept this is, it sets of all sorts of red flags for anyone who practices careful programming - could be why you're getting so many downvotes. So use with caution!