c++ integer division

旧巷老猫 提交于 2019-12-02 20:54:13

问题


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.

I want to get the result as a floating point number and then round up to the nearest int.

Something like this:

float result = rect.x/y;
int rounded = ceil(result);

How should I do this?


回答1:


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);



回答2:


You need to cast your variables.

float result = (float)rect.x / (float)y;
int rounded = ceil(result);



回答3:


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.



来源:https://stackoverflow.com/questions/13391664/c-integer-division

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!