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

后端 未结 9 1017
天命终不由人
天命终不由人 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:56

    Cast one of the integers/both of the integer to float to force the operation to be done with floating point Math. Otherwise integer Math is always preferred. So:

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

    Try this:

    class CalcV 
    {
          float v;
          float calcV(int s, int t)
          {
              float value1=s;
              float value2=t;
              v = value1 / value2;
              return v;
          } //end calcV
    }
    
    0 讨论(0)
  • 2020-11-22 08:58

    JLS Standard

    JLS 7 15.17.2. Division Operator / says:

    Integer division rounds toward 0. That is, the quotient produced for operands n and d that are integers after binary numeric promotion (§5.6.2) is an integer value q whose magnitude is as large as possible while satisfying |d · q| ≤ |n|. Moreover, q is positive when |n| ≥ |d| and n and d have the same sign, but q is negative when |n| ≥ |d| and n and d have opposite signs.

    This is why 1/2 does not give a float.

    Converting just either one to float as in (float)1/2 suffices because 15.17. Multiplicative Operators says:

    Binary numeric promotion is performed on the operands

    and 5.6.2. Binary Numeric Promotion says:

    • If either operand is of type double, the other is converted to double.
    • Otherwise, if either operand is of type float, the other is converted to float
    0 讨论(0)
提交回复
热议问题