2013-07-14 39 views
0

该程序模拟以固定垂直和水平速度以角度发射的物体的抛物线轨迹。它以终端控制台中显示的坐标输出数据。模拟抛物线抛物线轨迹的C代码提前终止

但是,程序只输出数据到第二行并终止,因此代码中的某处必定存在错误。我无法识别错误,所以我正在请求帮助!

#include <stdio.h> 
#include <stdlib.h> 

int main(void) { 
float lvelox; 
float lveloy; 
float xcord; 
float ycord; 
int stepcount; 
int step = 0; 

/* Initializing velocity */ 
{ 
    printf("Enter the initial h velocity of the ball:\n"); 
    scanf("%f", &lvelox); 
    printf("Enter the initial v velocity of the ball:\n"); 
    scanf("%f", &lveloy); 
} 

/* Obtain number of steps */ 
{ 
    printf("Enter the number of steps wanted:\n"); 
    scanf("%d", &stepcount); 
} 

/* formula for calculating initial position */ 
    if (step == 0) 
    { 
    xcord = 0; 
    ycord = 0; 
    step = step + 1; 
    printf("\n"); 
    printf("xcord, ycord, step\n"); 
    printf("\n"); 
    printf("%f, ", xcord); 
    printf("%f, ", ycord); 
    printf("%d\n", step); 
    } 

/* Loop method */ 
    if (step < stepcount) 
    { 
    lveloy = lveloy - 9.81; 
    xcord = xcord + lvelox; 
    ycord = ycord + lveloy; 
    step = step + 1; 
    printf("%f, ", xcord); 
    printf("%f, ", ycord); 
    printf("%d\n", step); 

    if (ycord < 0) 
    { 
    lveloy = (lveloy * -1); 
    lveloy = lveloy - 9.81; 
    xcord = xcord + lvelox; 
    ycord = ycord + lveloy; 
    step = step + 1; 
    printf("%f, ", xcord); 
    printf("%f, ", ycord); 
    printf("%d\n", step); 
    } 
    } 

    if (step >= stepcount) 
    { 
     return 0; 
    } 

} 
+1

附注:你的'printf'过于冗长。例如,你可以这样写:'printf(“%f,%f,%d \ n”,xcord,ycord,step);'。 –

+1

另外,'if(step == 0)'是多余的,因为'step'在那一点上保证为零。 –

+0

另一方面 - 注意:[**缩进C程序**](http://www.cs.arizona.edu/~mccann/indent_c.html) –

回答

1

你的“循环方法”不是一个循环!这是一个if语句。将其更改为可递增step的for循环,也许这将解决您的问题。

2

我想你想一个循环,而不是if,在您的代码:

if (step < stepcount) 

应该是:

while (step < stepcount) 
+0

你可以删除:'if(step> = stepcount)'该代码将工作find –

1

我想你误会了循环构造方式。你写的:

if (step == 0) { 
    // Starting code 
    ⋮ 
} 
if (step < stepcount) { 
    // Loop code 
    ⋮ 
} 
if (step >= stepcount) { 
    // Finishing code 
    ⋮ 
} 

而且你似乎认为事情会自动遍历这些测试。这不会发生。重写上面如下:

// Starting code 
⋮ 
for (step = 0; step < stepcount; ++step) { 
    // Loop code 
    ⋮ 
} 
// Finishing code 
⋮ 

注意,此代码会自动递增每个通step,所以你必须重新思考循环代码如何更新它。您似乎有条件地更新了两次,这是我不完全理解的,所以我不愿意规定具体的更改。