Divide returns 0 instead of float

前端 未结 4 703
-上瘾入骨i
-上瘾入骨i 2021-01-17 05:17

I was very surprised when I found out my code wasn\'t working so I created a console application to see where the problem lies and I\'ve got even more surprised when I saw t

4条回答
  •  情书的邮戳
    2021-01-17 05:58

    The division being performed is integer division. Replace

    float test = 140 / 1058;
    

    with

    float test = 140f / 1058; 
    

    to force floating-point division.

    In general, if you have

    int x;
    int y;
    

    and want to perform floating-point division then you must cast either x or y to a float as in

    float f = ((float) x) / y;
    

提交回复
热议问题