Not sure how to use functions and pass arguments

I am having a hard time passing arguments. The function fallingDistance is supposed to acquire a value for the variable time from the function seconds from 1-10 seconds. Function main is supposed to call function seconds 10 times. However the output of my program is "The distance is 0" ten times it does not do the calculations I want it to. What am I doing wrong?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;

//Prototypes
void seconds();
void fallingDistance (int time, double gravity = 9.8);

int main ()
{
       for (int count = 1; count <= 10; count++)
	seconds();

	system ("pause");
	return 0;
}

void seconds()
{
	static int value = 1;
	fallingDistance(value);
	value++;
}

void fallingDistance(int time, double gravity)
{

	double distance;
	distance = (1/2) * gravity * pow(time, 2.0);
	cout << "The distance is " << distance << endl;

}
Last edited on
Hi anton,

First up, please always use code tags:
http://www.cplusplus.com/articles/z13hAqkS/


Your problem is with this line:

distance = (1/2) * gravity * pow(time, 2.0);

The (1/2) does integer division and evaluates to 0. If you want FP arithmetic write (1.0/2.0)

Also, the pow function is very expensive for squaring numbers (it uses a series to calc the answer) , so just do (time * time) . Only use the pow function when the second arg isn't a whole number, as in pow(time, 1.2) , say.

You probably don't need 2 functions for this, can you figure out how to do it with 1 function.

A final point, avoid using magic numbers like 10 and 9.8 in your code - prefer to make them const variables, then refer to them by the variable name:

1
2
3
4
5
6
7
const unsigned int MaxTime = 10;
const double Gravity = 9.8;


for (int Time =  1; Time < MaxTime + 1; ++Time) { // always use braces even if 1 statement
    FallingDistance(Time, Gravity);
}


Good Luck
Last edited on
 
distance = (1/2) * gravity * pow(time, 2.0);


(1/2) is an integer expression, which will always be zero. It doesn't matter what the rest of the expression is, the result will always be zero.

PLEASE USE CODE TAGS (the <> formatting button) when posting code.
http://v2.cplusplus.com/articles/jEywvCM9/
It makes it easier to read your code and it also makes it easier to respond to your post.
Thanks, my program works now. And thank you for letting me know about code tags, I appreciate it.
Thank you as well because I was wondering how to use this code tag. @AbstractionAnon
Topic archived. No new replies allowed.