【发布时间】: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