How to round floating point numbers to the nearest integer in C?

前端 未结 11 671
鱼传尺愫
鱼传尺愫 2020-12-16 04:03

Is there any way to round numbers in C?

I do not want to use ceil and floor. Is there any other alternative?

I came across this code snippet when I Googled f

11条回答
  •  一整个雨季
    2020-12-16 04:51

    Round value x to precision p, where 0 < p < infinite. (f.ex. 0.25, 0.5, 1, 2,…)

    float RoundTo(float x, float p)
    {
      float y = 1/p;
      return int((x+(1/(y+y)))*y)/y;
    }
    
    float RoundUp(float x, float p)
    {
      float y = 1/p;
      return int((x+(1/y))*y)/y;
    }
    
    float RoundDown(float x, float p)
    {
      float y = 1/p;
      return int(x*y)/y;
    }
    

提交回复
热议问题