【问题标题】:C++ loop not working as expectedC++ 循环没有按预期工作
【发布时间】:2016-05-26 19:39:07
【问题描述】:

我想绘制 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;
    }
}

感谢您的帮助!

【问题讨论】:

  • 是否需要 ((theta % 360)
  • 在向他人寻求您编写的代码的帮助时,感谢 cmets 解释代码和正确/一致的缩进。
  • 您可能想想想当y = previousY + tan(theta * PI/180); 变为负数时会发生什么。我很确定rect[x][-anything] 不在您计划的议程中。仅供参考,正如所写,这将发生在 t 循环的第三次迭代,a 循环的第一次迭代中。
  • 所有if 语句都在for 循环中吗?
  • 您可以通过创建+1 或-1 的“加法”值并将其添加到x 来消除if 语句之一。改变方向时,将“加法”值乘以 -1。

标签: c++ arrays loops for-loop


【解决方案1】:

我真的不明白你的程序。我将核心简化为:

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 变量递增和递减。

不改变或不导致变量改变的语句已被提取出循环。

我建议您将上述程序的输出放入电子表格程序并让电子表格程序绘制它。

【讨论】:

    猜你喜欢
    • 2011-05-04
    • 1970-01-01
    • 1970-01-01
    • 2013-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多