Issues with trig functions

Please bare with me as this code I'm posting is not a finished product. It was only to see if my math was working correctly. This is a simple program to calculate the position over time of a projectile using physics kinematic equations. My problems are this:

It only works for the angle 45 degrees. And after I dunno, a few hundred outputs in the text file, it stops incrementing the time by .01 and jumps to something like 4.35001, then 4.36001 and etc. This isn't a big deal as far as accuracy goes... but it's annoying as hell when entering data into excel. Here is my code, any pointers and advice to help me solve the problem would be appreciated! Thanks! (please recall this is not a finished product, my final work looks much better than this):

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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include <iostream>
#include <cmath>
#include <fstream>

using namespace std;

int main()
{

	ifstream inFile;
	ofstream oFile;

	//inFile.open("data.txt");
	oFile.open("data.txt");
	float angle1;
	//float vi;
	//float vf;
	float vMag;
	//float vX;
	//float vY;
	float ypos;
	float xpos;

	float g = 4.900;

	int indicate;

	cout << "Please indicate by number which type of problem you would like to compute: " << endl;
	cout << "1 - 2D flight arc";
	cin >> indicate;

	if(indicate==1){

		cout << " Please enter your velocity magnitude: ";
		cin >> vMag;
		cout << "Please enter your angle above the X-axis at which the projectile is launched: ";
		cin >> angle1;

		float t = 1;
		ypos = ( (vMag)*(sin(angle1))*(t) - g*(t*t));
		xpos = ( (vMag)*(cos(angle1))*(t));
		oFile << "Time            X             Y" << endl;
		oFile << t << "         " << xpos << "         " << ypos << endl;
		while(ypos > 0){

			t = t + 0.01;

			ypos = ( (vMag)*(sin(angle1))*(t) - g*(t*t));
		    xpos = ( (vMag)*(cos(angle1))*(t));

			oFile << t << "         " << xpos << "         " << ypos << endl;
		}
	}




	return 0;

}
Problem 1:
1
2
xpos = cos(angle1)*t
ypos = sin(angle1)*t - g*t*t*0.5 //You're missing a divide by 2 here, if g isn't already halved. 


Problem 2:
To fix the precision problems, you just have to specify the output format. Since you're only stepping by 0.01 just fixing precision to 2 decimal places when outputting t should work:
1
2
oFile.precision(2);
oFile << fixed << t


In what way exactly does it "not work" for angles other than 45 deg? Crashing? Wrong output? No output?
Last edited on
Also, convert your angles from degrees to radians before passing them to sin/cos.
Wait, when you say "it only works for 45 degrees" you _are_ entering the angles that in radians right?

If not, that's the problem, the trig functions take radians, not degrees.

Edit: I see m4ster r0shi beat me to noticing that might be the problem
Last edited on
45c radians is one hell of an angle...
Topic archived. No new replies allowed.