Divide returns 0 instead of float

前端 未结 4 638
-上瘾入骨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;
    
    0 讨论(0)
  • 2021-01-17 06:01

    This will work the way you expect ...

    float test = (float)140 / (float)1058;
    

    By the way, your code works fine for me (prints a 0.1323251 to the console).

    0 讨论(0)
  • 2021-01-17 06:07

    You are using integer arithmetic and then converting the result to a float. Use floating-point arithmetic instead:

    float test = 140f / 1058f;
    
    0 讨论(0)
  • 2021-01-17 06:08

    The problem is that you are dividing integers and not floats. Only the result is a float. Change the code to be the following

    float test = 140f / 1058f;
    

    EDIT

    John mentioned that there is a variable of type ulong. If that's the case then just use a cast opeartion

    ulong value = GetTheValue();
    float test = 140f / ((float)value);
    

    Note, there is a possible loss of precision here since you're going from ulong to float.

    0 讨论(0)
提交回复
热议问题