Function determining distance object falls with time given as argument

Good evening guys. I'm working through this problem and feel like I've exhausted my resources.

This function is attempting to take the time in seconds as an argument and return the distance that it falls in that number of seconds. The equation for finding this is d = 1/2*g*t^2 where g (gravity) = 9.8.

The code compiles, but when executed it does not return ANYTHING. I must be missing something obvious. This forum has already be extremely valuable in helping me figure out functions.

Thanks again

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
 // function example
#include <iostream>
#include <math.h>       /* pow */



using namespace std;


double fallD(double t) // t is time 
{
	double d;
	double g = 9.8;

	d = (1 / 2)*g*pow(t,2);
	return d;
}

int main()
{
	double z;
	z = fallD(3);
	cout << "The result is " << z;

	
}
do you realize that when using integer math there are no fractions? So something like 1/2 would yield zero.
As jib said, (1 / 2) yields 0, to fix it make it (1.0 / 2).
This makes 1.0 a double and the other operand will also be implicitly converted to double during calculation

Edit: Or better yet, just divide g*pow(t,2) by 2 like:
 
d = g*pow(t,2) / 2;

This should work fine as the left operand is already a double, promoting 2 to double implicitly
Last edited on
closed account (48T7M4Gy)
It's important to know what jlb has highlighted as the problem and it's important to keep it simple,

d = 0.5 * g * t * t;
Last edited on
Thanks guys.

Being new at this makes me feel like I'm taking crazy pills sometimes. That did the trick! Thanks for the tip on keeping it simple kemort, t*t is much easier!
closed account (48T7M4Gy)
Cheers, no pills required - just experiment and practice :)

PS There's nothing wrong with pow except doing it the other way means for simple powers you don't have to look up the reference to remind yourself of the correct syntax. Sometimes there's no alternative.
Topic archived. No new replies allowed.