0

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

但是,程序只输出到第二行的数据并终止,所以代码中一定有错误。我无法识别错误,所以我请求帮助!

 #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;
   }

 }
4

3 回答 3

2

我认为您想要一个循环而不是if, 在您的代码中:

 if ( step < stepcount ) 

应该:

 while ( step < stepcount )
于 2013-07-14T09:16:53.553 回答
1

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

于 2013-07-14T09:16:47.930 回答
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在每次传递时都会自动递增,因此您必须重新考虑循环代码如何更新它。您似乎有条件地对其进行了两次更新,我对此并不完全理解,因此我犹豫是否要进行具体更改。

于 2013-07-14T09:25:02.873 回答