数学问题(增加和减少一个循环内的两个变量)(Mathematical issue (Increasing and deceasing two variables inside one loop))

编程入门 行业动态 更新时间:2024-10-23 07:19:56
数学问题(增加和减少一个循环内的两个变量)(Mathematical issue (Increasing and deceasing two variables inside one loop))

我有一个for循环,里面的整数x将从533增加到813.这意味着280增量。 在同一个循环中,我想在发生上述情况时将y的值从300减少到200。 这意味着当x是533时y必须是300而x是813时y必须是200.我知道这可以通过在每次迭代中将y的值减小100/280来实现。 但都是整数。

以下是我使用的一些代码示例,但它不工作:

for(int i = 0; i < b.getSize(); i++) { x = b.getCar(i).getPosX(); b.getCar(i).setPosX(++x); if(x >= ((getWidth() / 2) - 140) && x < ((getWidth() / 2) + 140)){ y = b.getCar(i).getPosY(); y = (double)(y - (10.0f / 28.0f)); b.getCar(i).setPosY((int)y); } }

我怎么可能做到这一点。 谢谢!

I have a for loop and inside that integer x will increase from 533 to 813. That means 280 increments. In side the same loop I want to decrease y's value from 300 to 200 when above happens. Which means when x is 533 y must be 300 and when x is 813 y must be 200. I know this can do by decrease y's value by 100/280 in each iteration. But both are integers.

Here are some code sample i used but it is not working.:

for(int i = 0; i < b.getSize(); i++) { x = b.getCar(i).getPosX(); b.getCar(i).setPosX(++x); if(x >= ((getWidth() / 2) - 140) && x < ((getWidth() / 2) + 140)){ y = b.getCar(i).getPosY(); y = (double)(y - (10.0f / 28.0f)); b.getCar(i).setPosY((int)y); } }

How can I possibly do this. Thanks!

最满意答案

有两种解决方案,简单和复杂。 简单的一个:

y = yoff + (int)( (double) height * x / width )

其中yoff = 300, height = -100, width = 813-533 。 基本上,你做一个浮点运算,然后你围绕结果。

或者,使用Bresenham线算法也可以使用纯整数运算来完成相同的操作,但这需要更多的代码。

There are two solutions, a simple and a complex one. The simple one:

y = yoff + (int)( (double) height * x / width )

where yoff = 300, height = -100, width = 813-533. Basically, you do a floating point operation and then you round the result.

Alternatively, the same can be done using pure integer math using the Bresenham line algorithm but that would take a lot more code.

更多推荐

本文发布于:2023-08-07 02:00:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1458992.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:变量   两个   数学   Mathematical   issue

发布评论

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

>www.elefans.com

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