Why does the following formula give an answer of 0:
float variable = (15 / 360) * SensorValue;
while converting to a decimal works just fine?
float variable = 0.042 * SensorValue;
Why does the following formula give an answer of 0:
float variable = (15 / 360) * SensorValue;
while converting to a decimal works just fine?
float variable = 0.042 * SensorValue;
Your values on the right in the first case are integers and are being evaluated as integers. You only try to turn it into a float when you plug in for variable on the left. So you’ve got a value round to 0, which you then stick in a float. In the second case, you have a float on the right so the right is being evaluated as a float.
Thanks for the quick reply.
I also tried creating “variable” as an int instead of float, and that also gave an answer of 0. Thoughts?
So would my first attempt have worked if I’d said it like so?
float variable = (15.0 / 360.0) * SensorValue
As @callen says, it’s because your’e doing integer math. You can force floating point math a couple of ways. Here’s one:
float variable = (15 / 360.0) * SensorValue;
Int this case, 360.0 is a floating point number, so the dividend will be converted to a float before the division takes place, as will the multiplicand “SensorValue” and all calculations will take place as floating point.
Here’s another way:
float variable = (15 / (float)360) * SensorValue;
That is called “casting.” The 360 is cast as a float; this causes the dividend and multiplicand to be “promoted” to floating point just as in the previous example.
This works as well:
float variable = ((float)15 / 360) * SensorValue;
But this does not:
float variable = (15 / 360) * (float)SensorValue;
That’s exactly what I would expect.
Yes.
When you divide 15 by 360, the whole number part of the answer is zero.
Gotcha. Thanks a ton!