[英]What other alternatives do I have for nested if statements for float variables going to infinity?
I'm trying to construct a code for a float
variables that does not rely on nested if statements unlike you can see in the following code-example. 我正在尝试为不依赖于嵌套if语句的
float
变量构造代码,与您在以下代码示例中看到的不同。
As you can see the higher the velocity of the ball, the longer the code would get. 如您所见,球的速度越高,代码就会越长。
Is there a shorter way to write the code or do I have to use the nested if-else statement for the variable of ball_vector_x when going up to infinity or just as example up to 100? 有没有更短的编写代码的方法,或者当上升到无穷大或例如达到100时,我是否必须对ball_vector_x变量使用嵌套的if-else语句?
counter is an int
variable starting at zero counter是一个从零开始的
int
变量
if(ball_vector_x == 4 || ball_vector_x == -4) {
counter = 1;
} else if(ball_vector_x == 5 || ball_vector_x == -5) {
counter = 2;
} else if(ball_vector_x == 6 || ball_vector_x == -6) {
counter = 3;
} else if(ball_vector_x == 7 || ball_vector_x == -7) {
counter = 4;
} else if(ball_vector_x == 8 || ball_vector_x == -8) {
counter = 5;
} else if(ball_vector_x == 9 || ball_vector_x == -9) {
counter = 6;
} else if(ball_vector_x == 10 || ball_vector_x == -10) {
counter = 7;
} else if(ball_vector_x == 11 || ball_vector_x == -11) {
counter = 8;
} else if(ball_vector_x == 12 || ball_vector_x == -12) {
counter = 9;
} else if(ball_vector_x == 13 || ball_vector_x == -13) {
counter = 10;
看来您的计数器始终是矢量-3.您不能这样做
counter = Math.abs(ball_vector_x)-3;
First: you can use Math.abs() to cut the number of comparisons by half. 首先:您可以使用Math.abs()将比较次数减少一半。
And then you could use a map to store all these pairs for example. 然后,您可以使用地图存储所有这些对。
But of course, the real answer is: you can express the relationship between those values using a simple formula. 但是,当然,真正的答案是:您可以使用一个简单的公式来表达这些值之间的关系。 That is always the solution to look out for.
始终是需要注意的解决方案。
Finally: the point that the other answers are missing to explain -avoid comparing floating point numbers using ==. 最后:缺少其他答案的要点-避免使用==比较浮点数。 Use epsilon based comparison instead.
请改用基于epsilon的比较。
This will check if ball_vector_x is negative or positive and then set counter equal to the value of i. 这将检查ball_vector_x是负还是正,然后将counter设置为等于i的值。
if (ball_vector_x >= 0) {
for (int i = 0; i < ball_vector_x; i++) {
if(i == ball_vector_x) {
counter = i - 3;
}
}
else {
for(int i = 0; i > ball_vector_x; i--) {
if (i == ball_vector_x) {
counter = (-1)*(i + 3); // I might've done the calculation wrong here
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.