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

前端 未结 11 651
鱼传尺愫
鱼传尺愫 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:46

    I think what you're looking for is: int n = (d - floor(d) > 0.5) ? ceil(d) : floor(d);

    0 讨论(0)
  • 2020-12-16 04:48

    just add 0.5 to the number and typecast it.. and print it by type casting it in integer.. otherwise you can go with round() inside which just pass the argument as the respective number.

    0 讨论(0)
  • 2020-12-16 04:49

    A general solution is to use rint() and set the FLT_ROUNDS rounding mode as appropriate.

    0 讨论(0)
  • 2020-12-16 04:49

    You may be able to use fesetround() in fenv.h (introduced in C99). The possible arguments are the macros FE_DOWNWARD, FE_TONEAREST, FE_TOWARDZERO, and FE_UPWARD but note that not all of them are necessarily defined - only the ones supported by the platform/implementation are. Then you can use the various round, rint and nearbyint functions in math.h (also C99). This way you can set the desired rounding behaviour once and call the same function regardless of whether or not the value is positive or negative.

    (With e.g. lround you usually need not even set the rounding direction for normal use to usually get what you want.)

    0 讨论(0)
  • 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;
    }
    
    0 讨论(0)
提交回复
热议问题