I have to do an operation with integers, very simple:
a=b/c*d
where all the variables are integer, but the result is ZERO whatever is the value of the parameters. I guess that it’s a problem with the operation with this type of data (int).
I solved the problem converting first in float and then in integer, but I was wondering if there is a better method.
The
/operator, when used with integers, does integer division which I suspect is not what you want here. In particular,2/5is zero.The way to work around this, as you say, is to cast one or more of your operands to e.g. a
float, and then turn the resulting floating point value back into an integer usingMath.floor,Math.roundorMath.ceil. This isn’t really a bad solution; you have a bunch of integers but you really do want a floating-point calculation. The output might not be an integer, so it’s up to you to specify how you want to convert it back.More importantly, I’m not aware of any syntax to do this that would be more concise and readable than (for example):