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

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

    the googled code works correctly. The idea behind it is that you round down when the decimal is less than .5 and round up otherwise. (int) casts the float into a int type which just drops the decimal. If you add .5 to a positive num, you get drop to the next int. If you subtract .5 from a negative it does the same thing.

提交回复
热议问题