0

我觉得自己像个白痴。当我将变量传递给函数时,它会产生一个奇怪的输出,如 6.2+e003 而不是变量所保存的值。我究竟做错了什么?

main 中的 x 和函数中的 x 不一样?

主要的:

int x, y;

while(system.WindowOpen())
{
    x++;
    y++;
    bg.Draw2D();
    bob.Think(x, y);
    riley.Think(x, y);
    system.Render(0);
}

类方法:

void Organism::Think(double x, double y)
{
    std::cout << "X: " << x << "\n";
    std::vector<double> food;
    food.push_back(x);
    food.push_back(y);
    std::cout << "VECTOR: " << food[0] << " " << food[1] << "\n";
    std::vector<double> path;
    if(refresh.IsTime()) {
        std::cout << "\nFOOD VECTOR: \n" << food[0]
                  << "\n" << food[1] << "\n";

        path = brian.GetOutput(food);


        organism.Translate2D(path[0], path[1]);

        if(organism.IsOffScreen2D(resX, resY) == 'l' )
            organism.SetPos2D(resX, organism.GetY());
        if(organism.IsOffScreen2D(resX, resY) == 'r')
            organism.SetPos2D(0, organism.GetY());
        if(organism.IsOffScreen2D(resX, resY) == 't')
            organism.SetPos2D(organism.GetX(), resY);
        if(organism.IsOffScreen2D(resX, resY) == 'b')
            organism.SetPos2D(organism.GetX(), 0);
    };

    font.DrawNumber2D(x, 50, 50);
    font.DrawNumber2D(y, 50, 100);
    organism.Draw2D();
}
4

2 回答 2

4

两者xy在这里都未初始化:

int x, y;

因此它们可以保持任何值,并且从中读取是未定义的行为。你应该初始化它们:

int x = 0
int y = 0;
于 2013-07-18T04:51:43.807 回答
0

我在向量的范围之外写作。我从使用[]运算符切换到使用.at()并立即发现了我的错误。只是有点内存损坏。我觉得很傻。谢谢大家!

于 2013-07-19T03:22:00.833 回答