/* a simulation of a cannonball flying in a vacuum */ #include #include #include float d2r(float); int main(int argc, char *argv[]){ float x, y, maxy = 0.0, xv, yv, deltaxv, deltayv, t, deltat, angle, velocity; /* check for proper usage */ if (argc != 4) { printf("Usage: cannon \n"); exit(1); } /* parse variables */ angle = atof(argv[1]); velocity = atof(argv[2]); deltat = atof(argv[3]); /* print out input */ printf("You entered:\n"); printf("Launch angle: %f\n", angle); printf("Launch velocity: %f\n", velocity); printf("Timestep: %f\n\n", deltat); /* calculate vectors */ /* remember trig functions want radians! */ xv = cos( d2r (angle)) * velocity; yv = sin( d2r (angle)) * velocity; printf("Vectors:\n"); printf("X velocity: %f\n", xv); printf("Y velocity: %f\n\n", yv); /* set initial conditions */ x = 0.0; y = 0.00001; /* make sure it's not zero initially */ t = 0.0; /* print headder */ printf("Time, X position, X velocity, Y position, Y velocity\n"); /* main loop */ while (y > 0.0) { printf("%f, %f, %f, %f, %f\n", t, x, xv, y, yv); t = t + deltat; x = x + xv * deltat; y = y + yv * deltat; if (y > maxy) maxy = y; deltayv = -9.8 * deltat; yv = yv + deltayv; } printf("%f, %f, %f, %f, %f\n", t, x, xv, y, yv); /* print some final numbers */ printf("\n\n"); printf("Maximum height: %f\n", maxy); printf("Maximum distance: %f\n", x); printf("Time to impact: %f\n", t); } float d2r(float degrees) { float radians; /* convert degrees to radians for trig calcs */ radians = degrees * 3.14159 / 180.0; return(radians); }