Is there a function to round a float in C or do I need to write my own?

后端 未结 7 1395
旧时难觅i
旧时难觅i 2020-11-27 07:02

Is there a function to round a float in C or do I need to write my own?

float conver = 45.592346543;

I would

7条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-27 07:29

    Just to generalize Rob's answer a little, if you're not doing it on output, you can still use the same interface with sprintf().

    I think there is another way to do it, though. You can try ceil() and floor() to round up and down. A nice trick is to add 0.5, so anything over 0.5 rounds up but anything under it rounds down. ceil() and floor() only work on doubles though.

    EDIT: Also, for floats, you can use truncf() to truncate floats. The same +0.5 trick should work to do accurate rounding.

提交回复
热议问题