-5

I am trying to figure out what this statement means and what the variable larg contains:

int larg;
larg = ((larg % 8 != 0) ? (int) (Math.floor(larg / 8.0) + 1) * 8 : larg);
Robo Mop
  • 3,485
  • 1
  • 10
  • 23

1 Answers1

1

The part

(larg % 8 != 0)

asks if larg does not divide without a remainder by 8. If so

(int) (Math.floor(larg / 8.0) + 1) * 8 

is executed which divides larg by 8, rounds down to discard the remainder and adds one, and then multiplies back by 8. This means find the next multiplum of 8 larger than larg.

This is put in a ternary operator ...? ... : ... which is an if-statement. So

larg =((larg % 8 != 0) ? (int) (Math.floor(larg / 8.0) + 1) * 8 : larg);

means: "If larg is not a multiple of 8, round up to the next multiple of 8, otherwise set it to itself". Another way to put it (as division of an integer by an integer discards the fraction)

if (larg % 8 != 0) {
    larg = ((larg / 8) + 1) * 8;
}

This code was most likely written by a semi-experienced programmer, who preferred a one-liner instead of the three-line if-statement. A more experienced programmer would know that readability is more important than keeping it on one line, so a future reader like you would understand it instead of having to ask here.

Thorbjørn Ravn Andersen
  • 73,784
  • 33
  • 194
  • 347
  • Since the intention is to round up to the next multiple of 8, an even more intuitive way of writing it would be `larg = Math.ceil(larg / 8.0) * 8;` without any conditional logic at all. – Dawood ibn Kareem Apr 01 '18 at 10:29
  • In your last example, you should mention that `larg` must also be integral for that to work. Although I now notice that the OP has updated the question to include the `int` declaration. – Boris the Spider Apr 01 '18 at 10:32
  • @DawoodibnKareem using doubles to do integer arithmetic is rarely the most efficient. – Thorbjørn Ravn Andersen Apr 01 '18 at 21:16