Calculate Time With Recursion?

Hey everyone! I have a quick question I was hoping to get help with. I need to write a recursive function that returns the amount of time needed to travel a distance. If the distance is 1 metre or less, then the amount of time will always be 1 minute. If the distance is greater than 1 metre, my function takes the distance, halves it, then repeats the function until the distance is less than 1. In doing so, it should keep track of the amount of times the function was executed, or the number of minutes in comparison. However, whenever I call my function, it always prints zero minutes no matter what distance. Here's what I have right now:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
using namespace std;

float spaceTime(float distance)//calculates the time need to travel a distance
{
	float timeCount=0;
	if(distance<=1)
	{
		return 1;
	}
	else if(distance>1)
	{
		return timeCount++;
	}
		return spaceTime(distance/2);
}

Thanks in advance! I can also post the main function if need be.
1
2
3
4
5
6
7
8
9
10
void recursive() {

	static int count = 0;

	if (count < 3) {
		count++;
		recursive();
	}

}
Your function always returns 1 on line 9 or 0 on line 13. Line 15 is unreachable.

1
2
3
4
5
6
7
8
float spaceTime(float distance)
{
    if (distance <= 1.0f)    // terminal condition
        return 1;
    
    // entire distance must still be traversed.
    return 2.0f * spaceTime(distance/2.0f);
}


As to the number of times the function is called, I'll leave that to you to figure out.
Topic archived. No new replies allowed.