Does the following Java statement have an error in it? If so, what is it?
P *= x/y
Does the following Java statement have an error in it? If so, what is it?
P *= x/y
It lacks a semicolon
If there's more errors, it depends on the types of P,x and y. They have to be number types
Looks perfectly fine apart from the aforementioned lack of a semicolon, and possible problems with type. That statement just divides x by y, multiplies that result by p, and places that value into p. p = (p*(x/y));
If P
is a primitive numeric data type (float, double, int, etc) it should probably be in lowercase. Uppercase variable names are typically reserved for constants in Java.
Also, since it translates to (P*(x/y))
, if x
and y
where int
and P
were float
or double
, you might not get the answer you expect.
If you're looking for "logical errors" and if the types are all integers, it's probably better to do:
P = (P*x)/y;
Because the current expression (IIRC) is equivalent to:
P = P*(x/y);
The latter expression may be less "accurate" if the types are integers. For example:
// evaluates to 3, as expected.
(5*3)/5;
However,
// Evaluates to 0 because of truncation.
5*(3/5);
So you need to be careful. In general division on integer expressions should be done as the final step.