为什么此计算(除法)返回错误的结果?

编程入门 行业动态 更新时间:2024-10-23 06:23:24
本文介绍了为什么此计算(除法)返回错误的结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我在使用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.

更多推荐

为什么此计算(除法)返回错误的结果?

本文发布于:2023-10-25 13:44:22,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1527121.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:除法   错误

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!