Modules in C++

Hi everyone,


I am trying to write a program that will display a table with "seconds" and "Distance". Where Seconds goes from 1-12 and the distance is displayed according to each second. However I am having trouble getting the distance variable to display any values. Help would be very much appreciated, by the way I am also using a second function in this program besides main(), called FallingDistance(). Thanks again for any help. Below is my code for the program so far.




#include <iostream>
using namespace std;

double FallingDistance(int, double);

int main()
{
int Seconds;
double Distance=0;
int distance;

cout << "Seconds Distance\n";
cout << "========================\n";

for (Seconds = 1; Seconds <= 12; Seconds++)
{
distance = FallingDistance(Seconds, Distance);
cout << Seconds << "\n\t\n\t" << Distance;
}
return 0;
}
double FallingDistance(int Seconds, double Distance)
{
const int g = 32.2;
int t = Seconds;
double distance;

distance = 1 / 2 * g*t*t;

return distance;
}
You are assigning value to distance, but trying to output Distance
C++ is case sencitive, you should watch case of variables.

Also:
const int g = 32.2; is the same as const int g = 32;, you cannot store floating point value in integer, it will be truncated.
Is std::distance a problem here too? If so, remove line 2.

Okay thank you.
And no it shows errors if I remove line 2.
But I am still having trouble with the prototype FallingDistance.
The program still will only display seconds 1-12, but the distance will not display at all.
You're still getting confused between the two variables distance and Distance, both of which are local variables in main().

You set distance to be the value returned by FallingDistance(), but you're outputting the value of Distance.

EDIT: You're also going to have a problem with integer division. The expression 1 / 2 is going to evaluate to 0, not 0.5.
Last edited on
I just corrected the variables to where there is only Distance.
And I also corrected the division problem, but for some reason my program is applying the calculations to the Seconds variable instead of the Distance variable.

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
#include <iostream>
using namespace std;

double FallingDistance(int, double);

int main()
{
	int Seconds;
	double Distance=0;

	cout << "Seconds         Distance\n";
	cout << "========================\n";

	for (Seconds = 1; Seconds <= 12; Seconds++)
	{
		Distance = FallingDistance(Seconds, Distance);
		cout << Seconds << "\n\n" << Distance;
	}
	return 0;
}
double FallingDistance(int Seconds, double Distance)
{
	double g = 32.2;
	int t = Seconds;
	
	Distance = 0.5 * g*t*t;

	return Distance;
}
You just screwed up your formatting. Try replacing line 17 with:

cout << Seconds << "\t\t" << Distance << endl;
Topic archived. No new replies allowed.