c-编写炮弹运动代码时出现问题



我正试图编写这段代码来计算炮弹的最终高度和飞行持续时间,而用户必须提供位移、初始速度和发射角度的值。没有任何编译错误,但我正在处理的更多的是一个逻辑错误。最终的高度值和持续时间都是完全错误的。此外,在我输入发射角度后,它不会立即计算高度和时间。相反,我需要按下向下键,然后输入以进行计算。我调用的编译器是[gcc-Wall-Weror-ansi-o task2.out task2.c-lm],后面跟着行[./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;       
}

假设一些情况(真空、平坦的环境、大的地球半径、通过2 Pi给出的全圆周角度,而不是360(,您的计算应该是

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

因为你需要除以速度的水平部分,而不是除以速度,然后乘以角度余弦。

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

因为最大高度是在半持续时间之后达到的,而不是在整个持续时间之后
这就是为什么重力相关加速度的积分(0.5*g*t*t(只需要减去一半。

需要输入更多内容而不仅仅是数字的问题已经被约翰的旧答案所涵盖,见那里。

It doesn't instantly calculate。那是因为你试图读取一个额外的数字

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

拆下那根线。下一行的公式计算时间。

高度的错误相同,

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

也拆下那根线。

最新更新