Unable to send value from function back to main
Feb 3, 2017 at 7:00am UTC
I'm not sure where my error is, can someone steer me in the right direction? I have to calculate the distance an object travels due to gravity based on how long the object falls. I'm unable to return a value to main and I only get the output "The object traveled 0.0 meters." Thanks!
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 34 35
#include <iostream>
#include <iomanip>
using std::cout;
using std::cin;
using std::endl;
using std::showpoint;
using std::fixed;
using std::setprecision;
//Function prototype for formula
double fallDistance(double time);
int main()
{
double distance;
double time;
//set output to show one decimal place
cout << fixed << showpoint << setprecision(1);
cout << "How long did the object fall? \n" ;
cin >> time;
cout << "The object traveled " << distance << " meters." << endl;
return 0;
}
double fallDistance(double time)
{
double distance;
const double grav = 9.8;
distance = (1/2) * grav * (time * time);
return distance;
}
Last edited on Feb 3, 2017 at 7:04am UTC
Feb 3, 2017 at 7:12am UTC
in main write just before line 22
distance = fallDistance( time);
as in:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
nt main()
{
double distance;
double time;
//set output to show one decimal place
cout << fixed << showpoint << setprecision(1);
cout << "How long did the object fall? \n" ;
cin >> time;
distance = fallDistance(time);
cout << "The object traveled " << distance << " meters." << endl;
return 0;
}
Last edited on Feb 3, 2017 at 7:14am UTC
Feb 3, 2017 at 2:36pm UTC
Also, in fallDistance(), change (1/2)
to (1.0/2)
.
1/2 divides integers, so it uses integer division which truncates the answer (0.5) to an integer (0).
Feb 3, 2017 at 3:41pm UTC
Thank you all, I was banging my head on this one. Appreciate it!
Topic archived. No new replies allowed.