I’m making a pretty simple Java program that calculates the distance a projectile will travel when launched at different angles and speeds. While it isn’t necessary to include angles above 180 degrees when talking about launch angle, I’m wondering why my code isn’t working the way I expect it to, in particular the following portion:
if((int)(angle / 180.0) % 2 != 0)
{
myDataArray[i][j] = 0.0;
}
If angle is a value between 180 and 360 (non-inclusive), then it should satisfy the condition, as should any equivalent angle (e.g. 540 to 720 non inclusive). Basically, whenever the firing angle is into the ground, the distance value should be zero.
The rest of the code is working fine, but this portion is being satisfied by ALL angle values 180 and up, meaning ALL those distances are zero. (This doesn’t make sense since a 365 degree launch angle should be the same as a 5 degree launch angle).
Am I doing something wrong, or is there an alternate condition I can use to get the desired result?
EDIT: Huge sigh….
There was no problem with the calculation, I’m just an idiot. I put the angle incrementor inside the else statement, meaning the first angle that read true for the if statement would be used for the rest of the program. Here’s the entire method code I had:
public void calcDistanceValues()
{
double angleStart = myAngleDegrees;
double speedStart = mySpeedMPH;
for(int i = 0; i < myNumRows; i++)
{
for(int j = 0; j < myNumColumns; j++)
{
if((int)(myAngleDegrees / 180.0) % 2 != 0)
{
myDataArray[i][j] = 0.0;
}
else
{
myDataArray[i][j] = 5280 * (Math.pow(mySpeedMPH,2)*Math.sin(2*Math.toRadians(myAngleDegrees))/78973);
myAngleDegrees += myUnitIncrement; //the problem is here*
}
}
mySpeedMPH += myUnitIncrement;
myAngleDegrees = angleStart;
}
mySpeedMPH = speedStart;
}
I think the test is correct, and the bug is in how it is being used. I wrote a simple test program to try it out:
The results were:
If I understand your requirements, it seems to be working.