整数溢出的错误

Nag*_*tri 3 c++ integer-overflow

这是我的OpenGL代码的一部分,我得到一个错误:

struct Ball {
    float x;
    float y;
    float rot;
    float dir;
    bool rmv;
    Ball* next;
};

Ball* curBall;
void addBall() {
    if (balls==NULL) {
        balls=new Ball;
        balls->next=NULL;
        curBall=balls;
    } else {
        curBall->next=new Ball;
        curBall=curBall->next;
        curBall->next=NULL;
    }
    curBall->x=((float)rand()/(float)(RAND_MAX+1))*(ww-1) +1;
    curBall->y=((float)rand()/(float)(RAND_MAX+1))*(wh-1) +1;
    curBall->dir=((float)rand()/(float)(RAND_MAX+1))*(2*PI-1) +1;
    curBall->rot=((float)rand()/(float)(RAND_MAX+1))*(359) +1;
    curBall->rmv=false;
}
Run Code Online (Sandbox Code Playgroud)
error :
In function ‘void addBall()’:
file.cpp:120: warning: integer overflow in expression
file.cpp:121: warning: integer overflow in expression
file.cpp:122: warning: integer overflow in expression
file.cpp:123: warning: integer overflow in expression
Run Code Online (Sandbox Code Playgroud)

Amb*_*ber 13

添加之前尝试转换RAND_MAX为浮点数.

curBall->x=((float)rand()/( ((float)RAND_MAX) +1))*(ww-1) +1;
Run Code Online (Sandbox Code Playgroud)

等等.RAND_MAX通常等于INT_MAX,整数可以容纳的最大值,因此在它仍被视为整数时将其加1,将其推过整数限制.

  • 另外我怀疑假设32位浮点数和int,`(static_cast <float>(RAND_MAX)+ 1.0f)== static_cast <float>(RAND_MAX)`因为浮点数中没有足够的位可用来表示每个整数和添加将只是截断. (2认同)