Simple division operation returning zero?

前端 未结 5 1441
醉酒成梦
醉酒成梦 2021-01-29 13:48

What am I missing?

float stepSize = 0.0f;
int activeCircleRadius = 10;
int numSteps = 24;

AiLog.v(\"init activeCircleRadius \" + activeCircleRadius + \" numStep         


        
相关标签:
5条回答
  • 2021-01-29 14:29

    Here both variables are integers so you are performing integer division:

    activeCircleRadius / numSteps
    

    The result of integer division is an integer. The result is truncated.

    To fix the problem, change the type of one (or both) variables to a float:

    float stepSize = 0.0f;
    float activeCircleRadius = 10;
    

    Or add a cast to float in the division expression:

    stepSize = (float)activeCircleRadius / numSteps;
    
    0 讨论(0)
  • 2021-01-29 14:42

    Don't do integer division

    stepSize = activeCircleRadius / (float)numSteps;
    

    In summary: Yes its because you divide activeCircleRadius by an integer.

    0 讨论(0)
  • 2021-01-29 14:43

    an integer division will give the result as 0. its 10/24 and not 10.0/24.0. you need to make one variable as double or float to get non zero answer.

    0 讨论(0)
  • 2021-01-29 14:44

    You are doing an integer division, and hence will not get any decimal places in your answer. Try changing:

    stepSize = activeCircleRadius / numSteps;
    

    to

    stepSize = activeCircleRadius / (float)numSteps;
    
    0 讨论(0)
  • 2021-01-29 14:50
     With all arithmetic operators in Java, the result has the type of the largest operator. For instance: 
    - float operator long => float 
    - int operator int => int 
    - int operator long => long 
    
    
    float stepSize = 0f;
            float activeCircleRadius = (float) 10.0;
            int numSteps = 24;
            stepSize = activeCircleRadius / numSteps;
    
    0 讨论(0)
提交回复
热议问题