变量在传递给函数时更改值

Variable changes value when passed to function?

本文关键字:函数 变量      更新时间:2023-10-16

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

主中的x和函数中的x不同?

main:

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();
}

此处未初始化xy

int x, y;

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

int x = 0
int y = 0;

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