c++ integer division

后端 未结 3 1239
抹茶落季
抹茶落季 2021-01-26 11:49

Say I\'ve got

SDL_Rect rect;
rect.x = 5; // rect.x is of type \"Uint16\"
int y = 11;

and I want to perform the operation rect.x/y

相关标签:
3条回答
  • 2021-01-26 12:16

    Cast either rect.x or y to float, and then do the division. This will force the entire division operation to take place in floating point.

    float result = rect.x/(float)y;
    int rounded = ceil(result);
    
    0 讨论(0)
  • 2021-01-26 12:17

    You need to cast your variables.

    float result = (float)rect.x / (float)y;
    int rounded = ceil(result);
    
    0 讨论(0)
  • 2021-01-26 12:17

    You can do this without any floating point types. If x and y are positive integers, then x divided by y, rounded up is (x+y-1)/y.

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