I have to write a program includes the function fallingDistance that accepts an object's falling time as an argument, then return the distance that the object has fallen during that time. It demonstrates the function by calling it in a loop that passes the values 1 - 10 as arguments and displays the return value.
Here's the mess of a code that I have so far; it's a mess but I'm not sure how to fix it.
/*
Name: Falling Distance
Description: User enters the falling time in seconds
and is shown the distance fallen in meters
*/
#include <iostream>
#include <cmath>
#include <string>
usingnamespace std;
//function prototypes
double fallingDistance(double);
//constants and variables
constdouble g = 9.8;
int t;
double d;
int main()
{
for(t = 1; t <= 10; t++)
fallingDistance(d);
system("pause");
return 0;
}
double fallingDistance(doublestatic distance)
{
staticdouble distance = 0.5*g*t*t;
cout << d << endl;
return distance;
}
Basically it would compile fine, but it would give me a column of 10 zeroes rather than actual results. C++ is a pretty weak subject for me, so I'm close to clueless as to what I did wrong here.
- Avoid to use global variables (there under the comment: //constants and variables)
- The argument of the function must be time t.
- In the function why did you use staticdouble distance ? The distance is variable, function of g and t.
- Try to put g inside the function.
- Because you type the distance (cout <<d...) don't need to return it.
So, make the corrections and try again.
#include <iostream>
#include <iomanip>
usingnamespace std;
void fallingSpeed(int);
int main()
{
cout << "\n\t Time(s) Speed(m/s)" << '\n';
cout << '\t';
for( int i = 0; i < 21; ++i)
cout << '~';
cout << '\n';
for(int t = 1; t <= 10; t++)
fallingSpeed(t);
system("pause");
return 0;
}
void fallingSpeed(int t) // the function type is void because it hasn't something to return.
{
constfloat g = 9.81; // g is in m/(s*s)
float v = g * t; // with t in seconds -> v in m/s.
cout << '\t';
cout << setw(4) << t << fixed << setprecision(3) << setw(14) << v << '\n';
cout << '\t';
for(int i = 0; i < 21; ++i) // some stuff to make a cute output.
cout << '~';
cout << '\n';
}
Nowadays, double should be used in preference to float for the same reason that we generally use at int with at least 32-bits rather than short which is usually 16-bits.
I use double type when the computing process needs a high precision. Here, for a simple multiplication, for 1 or 2 decimal positions, I consider float to be quite suitable. Please modify float with double and compare the results.
If this is your single question about my post then I wish you much success in the future!
Happy programming!