Hello,
I am trying to get into programming and I asked my cousin to send me his assignments from his uni class. It has been going pretty well but I have recently run into a problem.
here is the question:
In this question we are going to revisit our Ninja from Assignment 4. You are to write a C++ program that prompts the user for the distance between the Ninja and the sword, and uses a recursive function to calculate and return the number of seconds it will take the Ninja to pick up the sword. Use the following information:.
1. The Ninja covers half the distance from their current position to the sword each second.
2. At a distance of 1 meter or less, the Ninja can pick up the sword.
3. Zero seconds are required for the Ninja to actually pick up the sword once they are close enough..
4. At 1 second intervals, print how many meters the Ninja is from the sword.
5. The calculations should only be performed if the input is valid.
An example run of your program might look like this:
How far away is the ninja from his sword (in meters): 20
The ninja is 20 meters from the sword.
The ninja is 10 meters from the sword.
The ninja is 5 meters from the sword.
The ninja is 2.5 meters from the sword.
The ninja is 1.25 meters from the sword.
The ninja is 0.625 meters from the sword.
The ninja picks up the sword in 5 seconds.
# include <iostream>
usingnamespace std;
void ninja_distance(float a)
{
cout << "The ninja is " << a << " meters from the sword" << endl;
if (a > 1)
{
ninja_distance(a/2);
}
}
int main()
{
float number;
cout << " How far is the ninja from the sword? (in Meters) ";
cin >> number;
ninja_distance(number);
system("PAUSE");
return 0;
}
my problem is I need to count the number of times it does the recursive function (ie: the seconds) and I am not sure how to do this..
You could also change the data type of the function to return an integer value stating how many times to function called itself and pass the counter as a parameter.