因此,我希望数字保持在0到359之间,即使它超过360,361,362,363 ......等等,或者在-1,-2,-3,-4等等之下,每当我打电话时以下任何方法。如果它超过360我希望它变回0等,如果它变为-1我希望它改为359等我有这个代码它工作,但问题是,如果我改变了将标题数量减少或增加到5以上然后我只需继续制作其他if语句。编写代码的更好方法是什么,它会考虑标题的更高增量或减量?
heading = 3;
public void changeHeadingLeft() {
heading -= 5;
if (heading == -1) {heading = 359;}
else if (heading == -2) {heading = 358;}
else if (heading == -3) {heading = 357;}
else if (heading == -4) {heading = 356;}
else if (heading == -5) {heading = 355;}
heading = 358
public void changeHeadingRight() {
heading += 5;
if (heading == 360) {heading = 0;}
else if (heading == 361) {heading = 1;}
else if (heading == 362) {heading = 2;}
else if (heading == 363) {heading = 3;}
else if (heading == 364) {heading = 4;}
你可以不使用if和循环来做到这一点。
对于增量,请使用:
(header + amt) % 360
对于减量,使用:
(360 + header - (amt % 360)) % 360 //(amt % 360) incase amt > 360
例:
将标题增加5:
(0 + 5) % 360 = 5
溢出增加5到标题:
(360 + 5) % 360 = 5
减少5到标题:
(360 + 100 - (5 % 360)) % 360 = 95
使用下溢将5减少到标题:
(360 + 0 - (5 % 360)) % 360 = 355
使用下溢减少725到标题并且amt> 360:
(360 + 0 - (725 % 360)) % 360 = 355
您可以将它们添加为方法,然后您不必记住何时使用哪个。例如:
class CircularNumber{
private static final int BOUND = 360;
private int header;
public void add(int amt){
header = (header + amt) % BOUND;
}
public void deduct(int amt){
header = (360 + header - (amt % BOUND)) % BOUND;
}
}
通过在扣除之前对360扣除的数量应用模数,不需要使用循环来继续向标题添加360直到它变为正数。
对于模数运算符来说,这是一个完美的工作
heading = heading % 360;
这将使heading
循环从0到359,然后再次回到0
并且要处理否定的情况,是的,只需添加360直到heading
为正。
if (heading < 0) { heading += 360;}
适用于低至-360。同样地
if (heading >= 360) { heading -= 360; }
您可以使用以下功能:
public static int getHeading(int val)
{
val %= 360;
return (val < 0)? (val+360) :val;
}
看到它工作here in C++和here in Java:
class Test
{
public static int getHeading(int val)
{
val %= 360;
return (val < 0)? (val+360) :val;
}
public static void main (String[] args) throws java.lang.Exception
{
int[] vals = {-360, 360, -361, 361, -1, 1};
for(int i = 0; i< vals.length; i++)
{
System.out.println(vals[i] + " = " + getHeading(vals[i]));
}
}
}
OUTPUT:
-360 = 0
360 = 0
-361 = 359
361 = 1
-1 = 359
1 = 1
对于小于0的值
while(heading < 0){heading+=360;}
价值大于360
while(heading >= 360){heading-=360;}
使用while循环,它也可以使用小于-360的值
左更改:
heading = heading > 0 ? heading : 360 + heading
并为正确的改变:
heading = heading < 360 ? heading : heading - 360
import java.util.Scanner;
public class myClass {
public static void main (String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number: ");
int n = sc.nextInt();
while(n < 0){n+=360;}
while(n >= 360){n-=360;}
System.out.println(" number: " + n);
}
}