c++ - 变量改变它的值

标签 c++ class opengl

我有一个关于变量的非常奇怪的问题。在 OPENGL 渲染循环中调用几次后,一个变量无故更改其值 (verticesSize),而第二个变量 (verticesSize2) 没有... 相反,当我在程序的任何其他地方循环它们(使用 for)时,两者都保持正确的值。 不管我如何命名第一个变量,它总是会改变它的值,所以它一定是内存问题,但我不知道是什么导致了它。有什么想法吗?

cpp。文件

void CosmicBody::InitShape(unsigned int uiStacks, unsigned int uiSlices, float    fA,       float fB, float fC)
{
float tStep = (Pi) / (float)uiSlices;
float sStep = (Pi) / (float)uiStacks;

float SlicesCount=(Pi+0.0001)/tStep;
float StackCount=(2*Pi+0.0001)/sStep;
this->verticesSize=((int) (SlicesCount+1) * (int) (StackCount+1))*2;
    this->verticesSize2=((int) (SlicesCount+1) * (int) (StackCount+1))*2;
}

main.cpp

#include ....
CosmicBody one;

void renderScene(void)
{

std::cout<<one.verticesSize<<endl;
std::cout<<one.verticesSize2<<endl;

fps.calculateFPS(clock.elapsedTime);

glutSwapBuffers();
}

编辑 好的,我发现是哪一行导致了问题 在这个函数中函数 sprintf 使程序运行不正确。为什么另一个类的函数会导致这个? void FpsCalc::calculateFPS(unsigned int currentTime) {

frameCount++;
int timeInterval = currentTime - previousTime;

if(timeInterval > 1000)
{
    float fps = frameCount / (timeInterval / 1000.0f);
    previousTime = currentTime;
    frameCount = 0;
    sprintf(this->fps,"%f",fps); //this line makes mess 
}

#ifndef FPSCALC_H
#define FPSCALC_H
class FpsCalc
{
private:
int frameCount;
float previousTime;


public:
FpsCalc();
void calculateFPS(unsigned int currentTime);
char fps[5];

~FpsCalc(){};
};
#endif

最佳答案

fps 缓冲区不够大,无法容纳结果输出,导致未定义的行为:

sprintf(this->fps,"%f",fps);

我不确定默认精度但是在我的机器上:

float f = 1.1f;

产生:

1.100000

这是 9 个字符(7 位数字、句点和空终止符)。

您需要指定精度:

sprintf(this->fps, "%.2f", fps);

或者因为这是 C++,所以使用 std::ostringstreamstd::string 代替。

std::string fps;

...

float fps = frameCount / (timeInterval / 1000.0f);
std::ostringstream s;
s << fps;
this->fps = s.str();

关于c++ - 变量改变它的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12079808/

相关文章:

c++ - 继承运算符 +()

c++ - 将 ID 号映射到类

python - PyOpenGL 和 OpenGL 一样快吗?

c++ - 使用贝塞尔曲线创建圆角立方体?

c++ - C++ 中的射线网格交集或 AABB 树实现,开销很小?

c++ - 使用 boost over socket 发送和接收压缩文件

c++ - 从 GetAdaptersAddresses() 获取子网掩码

c++ - MySQL C API : How to work with row from mysql_fetch_row()?

scala - 如何使用 scala 类成员名称作为变量

c++ - 如何优化画圆?