Why does this calculation (division) return a wrong result?

后端 未结 1 1706
故里飘歌
故里飘歌 2021-01-29 15:08

I\'m having a strange problem with C++. In an OpenGL code I tried to compute a simple expression this way

void mouse(int button, int state, int x, int y){
    do         


        
1条回答
  •  攒了一身酷
    2021-01-29 15:22

    x is an int, 300 is an int, too. So the calculation will be done using integer arithmetics, i.e. ignoring the remainder. That is why the division will return 0 when you expect something between 0.0 and 1.0. For the result of the calculation, it does not matter which type of variable you save the result to.

    In your second example, you assign x-300 to double posx. So from this point on, you do floating point arithmetics leading to the expected result.

    Another way to make it work would be replacing 300 by 300.0.

    0 讨论(0)
提交回复
热议问题