Here is a program that models a tennis ball being thrown off the side of a 50 meter building.
The program should output the x, y, and velocity values at each time step.
However, I seem to be getting an infinite loop.
#include<stdio.h>
#include<math.h>
int main() {
//Intial values
float ax = 0; //acceleration in the horizontal direction
float ay = -9.8; //acceleration in the downward direction
float x = 0; //top of building at position 0
float y = 50; //building is height 50 m
float vx = 10*cos(30); //velocity in the horizontal direction = 10 m/s * cos(30);
float vy = 10*sin(30); //velocity in the vertical direction = 10 m/s * sin(30);
int time = 0; //time starts at 0 seconds
float deltaTime = 0.001; //increment time by .001 each iteration
//while ball is greater than 0, or above the ground which is at position 0
while(y > 0) {
time = time + deltaTime;
vx = vx + ax*deltaTime;
vy = vy + ay*deltaTime;
x = x + vx*deltaTime + (1/2*ax*deltaTime*deltaTime);
y = y + vy*deltaTime + (1/2*ay*deltaTime*deltaTime);
printf("x = %f, y = %f, vx = %f, vy = %f, time = %d, ", x,y,vx,vy,time);
}
system ("PAUSE");
return 0;
}
My guess is that y will never become smaller than 0, but because of my limited physics knowledge, I don’t know how I could fix it.
1/2 == 0 not 0.5
Since 1 and 2 are both integers this uses integer division which truncates to the closest integral number. Use
0.5fto get afloator just0.5to get a double.