How to make the division of 2 ints produce a float instead of another int?

后端 未结 9 1003
天命终不由人
天命终不由人 2020-11-22 08:24

In another Bruce Eckels exercise in calculating velocity, v = s / t where s and t are integers. How do I make it so the division cranks out a float?

         


        
相关标签:
9条回答
  • 2020-11-22 08:39

    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.

    0 讨论(0)
  • 2020-11-22 08:44

    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

    0 讨论(0)
  • 2020-11-22 08:45

    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.

    0 讨论(0)
  • 2020-11-22 08:49

    You can cast even just one of them, but for consistency you may want to explicitly cast both so something like v = (float)s / (float)t should work.

    0 讨论(0)
  • 2020-11-22 08:50

    To lessen the impact on code readabilty, I'd suggest:

    v = 1d* s/t;
    
    0 讨论(0)
  • 2020-11-22 08:56

    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;
    
    0 讨论(0)
提交回复
热议问题