/* Program written by Michael Hoshino and Howard Li * * Assignment 1 */ #include #include #include #include #define DELTA 0.01 #define G 9.81 #define PI 3.14159265 double simulate (double, double, double, double); int main (void) { double d, v, angle_in_deg = 0, angle_in_rad; double x0, y0, vx0, vy0, distance_of_throw, precise_angle_1, precise_angle_2; char test_random, guess_again; /* * Uses the system time as an argument for srand to set the seed used for randomly generated values */ srand(time(0)); printf("Enter the letter 'y' if you would like to use random values> "); scanf(" %c", &test_random); if (test_random == 'y') { d = 60 * (rand()*1.0)/RAND_MAX + 60; v = 20 * (rand()*1.0)/RAND_MAX + sqrt(d*G); } else { d = 100; v = sqrt(d*G) + 10; } /* * Keeps asking user for angle of throw until the ball lands within 10 meters of home plate or until user quits */ do { printf("\nThe fielder is %5.1lf meters from home plate.\n", d); printf("He throws the ball at a speed of %5.2lfm/s (%6.2lfkm/hr).\n\n", v, (v*3.6)); angle_in_deg = 0; while (angle_in_deg <= 0 || angle_in_deg >= 90) { printf("Please enter the angle of the throw, between 0 and 90 degrees, so that\n"); printf("the ball lands at the home plate. > "); scanf("%lf", &angle_in_deg); if (angle_in_deg <= 0 || angle_in_deg >= 90) { printf("\nThe angle of the throw MUST be between 0 and 90 degrees, NOT including 0 and 90.\n"); } } angle_in_rad = (PI * angle_in_deg)/180.0; x0 = d * -1; y0 = 0.0; vx0 = v * cos(angle_in_rad); vy0 = v * sin(angle_in_rad); distance_of_throw = simulate (x0, y0, vx0, vy0); if (distance_of_throw > 10) { printf("\n\nThe ball flew long by %6.1lf meters.", distance_of_throw); printf("\n\nEnter the letter 'y' if you would like to guess again. > "); scanf(" %c", &guess_again); } else if (distance_of_throw < -10) { printf("\n\nThe ball landed short by %6.1lf meters.", distance_of_throw * -1.0); printf("\n\nEnter the letter 'y' if you would like to guess again. > "); scanf(" %c", &guess_again); } else { printf("\n\nCongratulations! You picked a great angle!\n"); } } while(guess_again == 'y'); /* *Calculates the precise angles such that the ball lands directly on the home plate */ precise_angle_1 = 0.5 * (180.0/PI) * asin((d*G)/pow(v, 2)); precise_angle_2 = 90.0 - precise_angle_1; printf("\nThe calculated angles are %5.2lf degrees and %5.2lf degrees.\n", precise_angle_1, precise_angle_2); } /* * The "simulate" method calculates the distance and height of the ball every DELTA seconds */ double simulate (double x0, double y0, double vx0, double vy0) { double x = x0, y = y0, vy = vy0, t = 0, xlast, ylast, tlast; while(y >= 0) { if ((int)(t * 100) % 100 == 0) printf("\nt = %-5.2lf x = %-7.1lf y = %-5.2lf", t, x, y); xlast = x; ylast = y; tlast = t; t += DELTA; vy -= G * DELTA; x += vx0 * DELTA; y += vy * DELTA; } printf("\nt = %-5.2lf x = %-7.1lf y = %-5.2lf", tlast, xlast, ylast); return xlast; }