为什么此计算(除法)返回错误的结果? [英] Why does this calculation (division) return a wrong result?
问题描述
我在使用C ++时遇到一个奇怪的问题.在OpenGL代码中,我试图以此方式计算一个简单的表达式
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){
double posx = (x-300)/300;
double posy = -1*(y-300)/300;
switch(button){
case GLUT_LEFT_BUTTON:
if(state == GLUT_DOWN){
if(count < max){
particles[count].x = posx;
particles[count].y = posy;
particles[count].active = true;
count++;
}
glutPostRedisplay();
}
break;
default:
break;
}
}
但是由于某种原因,每个粒子都出现在屏幕中央.奇怪的是,当我用
替换 double posx =(x-300)/300
but for some reason every particle appear on the center of screen. Strangely when I replace double posx = (x-300)/300
with
double posx;
posx = x-300;
posx = posx/300;
(与y相同),代码有效...有人知道为什么会这样吗?也许我做错了是一件很简单的事情.自从我使用C ++以来已经有很多年了,如果这是我的一个简单错误,对不起.
(same for y) the code works... Anyone knows why it is happening? Maybe it is a very simple thing that i'm doing wrong. It's been ages since I used C++, so sorry if it was a simple mistake of mine.
推荐答案
x
是 int
, 300
是 int
也是.因此,计算将使用整数算术完成,即忽略余数.这就是为什么当您期望介于 0.0
和 1.0
之间的值时,除法将返回 0
的原因.对于计算结果,将结果保存到哪种类型的变量都没有关系.
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.
在第二个示例中,您将 x-300
分配给 double posx
.因此,从这一点开始,您将进行浮点运算以得到预期的结果.
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.
使其工作的另一种方法是将 300
替换为 300.0
.
Another way to make it work would be replacing 300
by 300.0
.
这篇关于为什么此计算(除法)返回错误的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!