1

I'm trying to write this code that calculates the final height and duration of flight for a projectile, while the user has to provide values for displacement, initial velocity, and launch angle. There aren't any compilation errors, but it's more of a logical error I'm dealing with. The final height value is completely wrong as well as the duration. Also after I enter the launch angle it doesn't instantly calculate the height and time. Instead I need to press the down key and then Enter for it to calculate. The compiler I call is [ gcc -Wall -Werror -ansi -o task2.out task2.c -lm] followed by the line [./task2.out]

#include <stdio.h> /* access to scanf, printf functions */
#include <math.h> /* access to trignometric functions */
#define g 9.8 /* acceleration due to gravity constant */
int main(void){
    double v, theta, t, x, h2;
    /* v = initial velocity
    theta = launch angle
    t = time
    x = horizontal displacement
    h2 = final height
    */

    printf("Enter range of projectile>");
    scanf("%lf", &x); /* assigned x as a long float */

    printf("Enter velocity>");
    scanf("%lf", &v); /* assigned v as a long float */

    printf("Enter angle>");
    scanf("%lf", &theta); /* assigned theta as a long float */

    scanf("%lf", &t); /* assigned t as a long float */
    t = x/v*cos(theta); /* formula for time */

    scanf("%lf", &h2); /* assigned h2 as a long float */
    h2 = (t*v*sin(theta)) - (0.5*g*t*t); /* formula for height */

    printf("Projectile final height was %.2lf metres./n", h2); 
    printf("Projectile duration was %.2lf seconds", t );

    return 0;       
}
Gerhardh
  • 11,688
  • 4
  • 17
  • 39
garageman
  • 25
  • 3

2 Answers2

2

Assuming a few things (vacuum, flat environment, large earth radius, angle given via 2 Pi for a full cirlce, not 360), your calculations should be

t = x/(v*cos(theta));

because you need to divide by the horizontal part of velocity, not by velocity and then multiply by angles cosine.

h2 = (t*v*sin(theta)) - (0.25*g*t*t);

Because the maximum height is reached after hald the duration, not after the full duration.
That is why the integral of gravity-related acceleration (0.5 * g * t * t) only needs to be subtracted half.

The problem with the need to enter more things than just the numbers is covered already by the older answer by john, see there.

Yunnosch
  • 26,130
  • 9
  • 42
  • 54
1

It doesn't instantly calculate. That's because you are trying to read an extra number

scanf("%lf", &t); /* assigned t as a long float */

Remove that line. The formula on the next line calculates the time.

Same error for the height,

scanf("%lf", &h2); /* assigned h2 as a long float */

Remove that line as well.

john
  • 85,011
  • 4
  • 57
  • 81