본문 바로가기

문제로 함께하는 C언어

문제6. 탄도 위치 계산

문제:

어떠한 물체를 포물선 형태로 던진다고 하자. 1초, 2초, 3초 후 물체의 위치를 출력하여라.


단,

1. 물체의 초기 위치는 (0,0)이다.

2. x축 방향 초기 속도, y축 방향 초기 속도는 각 20m/s이다.

3. 중력가속도 g는 9.8로 계산한다.


4. 시간에 따른 물체의 위치 (x, y)는 다음과 같다.


여기서 x_0, y_0는 물체의 초기 위치이며, v_x는 x축 방향의 초기 속도, v_y는 y축 방향의 초기속도, g는 중력가속도, t는 시간이다.


5. 중력 가속도, 초기 위치, 초기 속도를 상수로 정의하시오.

6. for문을 사용하지 마시오.


화면:


해결방안:


5개의 float형 상수를 선언-정의한다.

초기위치(startX, startY), 초기속도(velocityX, velocityY), 중력가속도(gravity)


2개의 float형 변수와 1개의 int형 변수를 정의한다.

float: 시간에 따른 위치(currentX, currentY)

int: 시간(time)


초기 위치와 속도를 출력한다.


time의 값을 바꿔가면서 currentX, currentY의 값을 공식에 따라 대입하고 출력한다.(1초, 2초, 3초)


소스:


#include <stdio.h>

int main(void){
 const float startX = 0;
 const float startY = 0;
 const float velocityX = 20;
 const float velocityY = 20;
 const float gravity = 9.8;
 
 float currentX, currentY;
 int time;
 
 printf("startX, startY = ( %f, %f ) \n", startX, startY);
 printf("(initial) velocityX, velocityY = ( %f, %f ) \n", velocityX, velocityY);
 
 time = 1;

 currentX = startX + velocityX * time;
 currentY = startY + velocityY * time - 0.5 * gravity * time * time;
 
 printf("On %d sec, the object is located on: < %f, %f > \n", time, currentX, currentY);
 
 time = 2;

 currentX = startX + velocityX * time;
 currentY = startY + velocityY * time - 0.5 * gravity * time * time;
 
 printf("On %d sec, the object is located on: < %f, %f > \n", time, currentX, currentY);
 
 time = 3;

 currentX = startX + velocityX * time;
 currentY = startY + velocityY * time - 0.5 * gravity * time * time;
 
 printf("On %d sec, the object is located on: < %f, %f > \n", time, currentX, currentY);
 
 return 0;
}