1

Ok so im trying to make a program and i need to have the counter start at -3 and go down by 2, but every other number has to be a positive: for example:

-3, 5, -7, 9, -11, 13, -15, 17, -19,...

any input?

I made a successful program but i feel like this is not very efficient.

    while ("expression")
    {
        if (j % 4 == -1) //checks if number should be negative
            j = Math.abs(j);

        if (j > 0) //makes counter a negative
            j = -j;

        j -= 2; //goes down by 2
    }
4

5 回答 5

10

您可以使用for循环和 signSwitcher 变量:

int signSwitcher = 1;
for (int x = -3; expression; x -= 2, signSwitcher *= -1) {
    int counter = x * signSwitcher;
}
于 2013-05-17T23:26:09.070 回答
7

哎呀,你们都想得太辛苦了。明显和可读的有什么问题

if (counter > 0)
   counter = -1*(counter+2);
else
   counter = -1*(counter-2);
于 2013-05-17T23:41:47.613 回答
2

您正在做的实际上是在每个条目中添加 2,然后翻转标志。

int current = 1;
float sign = 1.0f;
while(current < 100) {
    current += 2;
    sign = Math.signum(sign)*-1.0f;
    System.out.println(sign*current);
}

这只是将最后一个条目的符号乘以 -1.0(这将使符号翻转)。

于 2013-05-17T23:31:12.577 回答
1

也使用模数:

public static void main(String[] args) {
    for (int i = 3; i < 20; i += 2) {
        int sign = ((i + 1) % 4 == 0 ? 1 : -1);
        System.out.println(i * sign);
    }
}
于 2013-05-17T23:33:41.637 回答
0
int increment = 2;
while ("expression")
{
    j += increment * (Math.abs(j)) + increment;
    increment *= -1;
}

那这个呢?

很容易

于 2013-05-17T23:40:06.420 回答