变量在传递给函数时更改值
Variable changes value when passed to function?
我觉得自己像个白痴。当我把一个变量传递给函数时,它会产生一个奇怪的输出,比如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();
}
此处未初始化x
和y
:
int x, y;
因此,它们可以持有任何价值,从中读取是未定义的行为。您应该初始化它们:
int x = 0
int y = 0;
我在向量的边界之外进行编写。我从使用[]
操作符切换到使用.at()
操作符,并立即发现了我的错误。只是有点内存损坏。我觉得很傻。谢谢大家!
相关文章:
- 未使用的C++未优化的静态成员函数/变量
- 内联函数/变量的外部链接
- 同一函数中的静态函数变量初始化顺序
- 将非静态成员函数C 的使用无效,而将成员功能作为函数变量
- 如何从doxygen输出中排除类的无证件成员函数/变量
- 如何在LUA C API中分配全局LUA函数变量
- 如何将函数变量传递给C lambda函数
- 通过另一个C++函数更改函数变量
- c++11 lambda 真的支持闭包吗?函数变量中存在语义冲突
- C++:静态成员不能在声明时定义,但静态函数变量可以?
- apache-frift是否支持函数变量作为参数
- 类函数/变量在使用之前必须声明
- 函数变量去哪里
- 无法使用函数变量?错误表达式必须具有类类型
- 如何在main中使用函数变量
- 每当尝试打印函数变量时,C++ cout 错误
- 是否存在查看成员函数/变量的整洁等效项
- 访问友元类之间的函数变量
- 函数到函数变量
- 一个定义规则是否强制创建一个静态函数变量