【问题标题】:Problem with writing code for projectile motion为弹丸运动编写代码的问题
【发布时间】:2020-03-24 09:19:56
【问题描述】:

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

【问题讨论】:

  • 请在所有情况下初始化变量并检查scanf()的返回值。
  • 您从用户那里得到 t,然后立即用计算结果覆盖它。为什么?
  • 如果您在扫描后立即打印所有输入值,您会看到什么?
  • 为什么不使用调试器?
  • 要修复错误的值,请尝试 t = x/(v*cos(theta));,这可能会修复其中一个,具体取决于 theta 是什么。你期待哪个单位?度数(360)?弧度(2 Pi)?

标签: c projectile


【解决方案1】:

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

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

删除该行。下一行的公式计算时间。

同样的高度误差,

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

也删除该行。

【讨论】:

  • 实际上是两次。但这如何解释错误的值?
  • 你的意思是“不要求它,例如printf("Enter time&gt;");
  • @Yunnosch 是的,我错过了。我不知道错误的值,但不妨一次修复一个错误。
  • 这就是不鼓励多问的原因。
【解决方案2】:

假设有几件事(真空、平坦的环境、大地球半径、通过 2 Pi 给出的完整圆的角度,而不是 360),您的计算应该是

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

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

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

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

john 的旧答案已经涵盖了需要输入更多内容而不仅仅是数字的问题,请参阅那里。

【讨论】:

    猜你喜欢
    • 2019-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多