C ++循环不能按预期工作

时间:2016-05-26 19:39:08

标签: c++ arrays loops for-loop

我想绘制x和y变量在数组中的位置,并且当x或y值大于其在数组中的相应维度时,它们应该改变方向。但是,当我运行程序时,Y值不断上升。我是C ++的新手,所以非常感谢任何帮助。这是我的代码:

#define PI 3.14159265
#include <iostream>
#include <tgmath.h>

int timeRun = 0;
int rect[500][1000] = {0};
int theta = 50;
int x = 0;
float y = 0;
float previousY = 0;
int yGo;
int dir = 0;//0 = right; 1 = left;
int main()
{
    for(int a = 30; a<=89; a=a+1){
        memset(rect,0,sizeof(rect));
        x = 0;
        y = 1;
        theta = a;
        std::cout << theta;
        int sum = 0;
        for(int t = 0; t<1000;t=t+1){
            y = previousY + tan(theta * PI/180);
            previousY = y;
            yGo = floor(y);
            rect[x][yGo] = 1;
            if(dir==0){
                x++;
            }
            if(dir==1){
                x--;
            }
            if(x>499 && dir==0){
                dir = 1;
            if(theta%360 >= 270 && theta%360 <= 360){
                theta+=(a-180);
            }

        }
        if(x<1 && dir==1){
            dir = 0;
            if(theta%360 >= 0 && theta%360 <= 90){
                theta+=(180-a);
            }
        }
        if(y>998 && dir ==0){
            theta+=(a-180);
        }
        if(y>998 && dir ==1){
            theta+=(180-a);
        }
        if(y<1 && dir ==0){
            theta+=(180-a);
        }
        if(y<1 && dir ==1){
            theta+=(a-180);
        }
    }
    for ( int i = 0; i < 500; i++ ){
        for ( int j = 0; j < 1000; j++ ){
            sum+=rect[i][j];
        }
    }
        std::cout << sum;
    }
}

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

我真的不明白你的节目。我将核心简化为:

static const float radian_conversion = 3.14159264f / 180.0f;
int     x = 0;
float   y = 0.0f;
int     theta = 30;
int     dir_add = 1;
cout << "t | x | y | theta" << endl;
const float y_increment = tan(theta * radian_conversion);
for (int t = 0; t < 1000; ++t)
{
    y = y + y_increment;
    cout << t << "|" << x << "|" << y << "|" << theta << "\n";
    int y_index = floor(abs(y));
    rect[x][y_index] = 1;
    x = x + dir_add;
    if ((x > 499) || (x < 1))
    {
        dir_add = dir_add * -1;
    }
}

我还展示了如何使x变量递增和递减。

不会更改或不会导致变量更改的语句已从循环中提取出来。

我建议您将上述程序的输出转换为电子表格程序,并让电子表格程序绘制它。

相关问题