基于小型物理程序的无限循环

时间:2011-05-20 15:03:08

标签: c physics

这是一个模拟从50米建筑物侧面抛出的网球的程序。 程序应在每个时间步输出x,y和速度值。 但是,我似乎得到了一个无限循环。

 #include<stdio.h>
 #include<math.h>

 int main() {

     //Intial values 
     float ax = 0; //acceleration in the horizontal direction
     float ay = -9.8; //acceleration in the downward direction
     float x = 0; //top of building at position 0 
     float y = 50; //building is height 50 m
     float vx = 10*cos(30); //velocity in the horizontal direction = 10 m/s * cos(30); 
     float vy = 10*sin(30); //velocity in the vertical direction = 10 m/s * sin(30);     
     int time = 0; //time starts at 0 seconds
     float deltaTime = 0.001; //increment time by .001 each iteration

     //while ball is greater than 0, or above the ground which is at position 0
     while(y > 0) {

     time = time + deltaTime;
     vx = vx + ax*deltaTime;
     vy = vy + ay*deltaTime;
     x = x + vx*deltaTime + (1/2*ax*deltaTime*deltaTime);
     y = y + vy*deltaTime + (1/2*ay*deltaTime*deltaTime);     

     printf("x = %f, y = %f, vx = %f, vy = %f, time = %d, ", x,y,vx,vy,time);

     }
     system ("PAUSE"); 
     return 0;

 }

我的猜测是y永远不会小于0,但由于我有限的物理知识,我不知道如何解决它。

5 个答案:

答案 0 :(得分:8)

1/2 == 0不是0.5

由于1和2都是整数,因此使用整数除法,它将截断为最接近的整数。使用0.5f获取float0.5获得双倍。

答案 1 :(得分:1)

time是一个int,而不是一个浮点数;所以不会永远保持零吗?

答案 2 :(得分:1)

将时间声明为float,而不是int:由于这个原因,它在当前代码中根本没有变化。 <math.h>中的三角函数接受弧度,而非度数。

答案 3 :(得分:0)

查看术语

y = y + vy*deltaTime + (1/2*ay*deltaTime*deltaTime);   

答案 4 :(得分:0)

如果您有兴趣了解您的代码,只需要很少修改就可以在C#中没有杀手循环完成:

            float ax = 0; //acceleration in the horizontal direction
            float ay = -9.8f; //acceleration in the downward direction
            float x = 0; //top of building at position 0 
            float y = 50; //building is height 50 m
            float vx = 10f * (float)Math.Cos(30); //velocity in the horizontal direction = 10 m/s * cos(30); 
            float vy = 10 * (float)Math.Sin(30); //velocity in the vertical direction = 10 m/s * sin(30);     
            float time = 0; //time starts at 0 seconds
            float deltaTime = 0.001f; //increment time by .001 each iteration

            //while ball is greater than 0, or above the ground which is at position 0
            while (y > 0)
            {

                time = time + deltaTime;
                vx = vx + ax * deltaTime;
                vy = vy + ay * deltaTime;
                x = x + vx * deltaTime + (1 / 2 * ax * deltaTime * deltaTime);
                y = y + vy * deltaTime + (1 / 2 * ay * deltaTime * deltaTime);

                Console.WriteLine("x = {0}, y = {1}, vx = {2}, vy = {3}, time = {4}, ", x, y, vx, vy, time);

            }
            Console.ReadKey();

我做的唯一修改就是Cos和Sin上的演员阵容以及更改浮动时间。  并在一些初始值(如铸造)之后添加'f'。

这可能不是C的真正答案,但它可能是一个线索?