Dividing an integer by an integer gives an integer result. 1/2 yields 0; assigning this result to a floating-point variable gives 0.0. To get a floating-point result, at least one of the operands must be a floating-point type. b = a / 350.0f; should give you the result you want.
When dividing two numbers of the same type (integers, doubles, etc.) the result will always be of the same type (so 'int/int' will always result in int). In this case you have double var = integer result which casts the integer result to a double after the calculation in which case the fractional data is already lost.
According to Python 3 documentation, Python when divided by integer, will generate float despite expected to be integer.
In Python 2, the only standard division operator is “/”. If both values are integers, the result is an integer. If either of the values is the float, the return is the float value. To perform float division in Python 2, import the division package __future__ module and then use the “\\” operator to get the result.
Just cast one of the two operands to a float first.
v = (float)s / t;
The cast has higher precedence than the division, so happens before the division.
The other operand will be effectively automatically cast to a float by the compiler because the rules say that if either operand is of floating point type then the operation will be a floating point operation, even if the other operand is integral. Java Language Specification, §4.2.4 and §15.17
Try:
v = (float)s / (float)t;
Casting the ints to floats will allow floating-point division to take place.
You really only need to cast one, though.
Cast one of the integers to a float to force the operation to be done with floating point math. Otherwise integer math is always preferred. So:
v = (float)s / t;
To lessen the impact on code readabilty, I'd suggest:
v = 1d* s/t;
You can cast the numerator or the denominator to float...
int operations usually return int, so you have to change one of the operanding numbers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With