在 C 中将正值四舍五入到小数点后两位 [英] Round positive value half-up to 2 decimal places in C

查看:64
本文介绍了在 C 中将正值四舍五入到小数点后两位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常,四舍五入到小数点后两位很容易

Typically, Rounding to 2 decimal places is very easy with

printf("%.2lf",<variable>);

但是,舍入系统通常会舍入到最近的偶数.例如,

However, the rounding system will usually rounds to the nearest even. For example,

2.554 -> 2.55
2.555 -> 2.56
2.565 -> 2.56
2.566 -> 2.57

我想要实现的是

2.555 -> 2.56
2.565 -> 2.57

事实上,四舍五入在C中是可行的,但仅适用于Integer;

In fact, rounding half-up is doable in C, but for Integer only;

int a = (int)(b+0.5)

所以,我想知道如何在正值上使用 2 个小数位而不是整数来执行与上述相同的操作,以实现我之前所说的打印.

So, I'm asking for how to do the same thing as above with 2 decimal places on positive values instead of Integer to achieve what I said earlier for printing.

推荐答案

不清楚您是真的想要四舍五入",还是四舍五入"零",这需要对负值进行不同的处理.

It is not clear whether you actually want to "round half-up", or rather "round half away from zero", which requires different treatment for negative values.

单精度二进制 float 至少精确到 6 位小数,double 为 20,因此通过 DBL_EPSILON(在 float.h 中定义)微调 FP 值将对于 n.nn5 值,通过 printf( "%.2lf", x ) 向上舍入到下一个 100.不影响非 n.nn5

Single precision binary float is precise to at least 6 decimal places, and 20 for double, so nudging a FP value by DBL_EPSILON (defined in float.h) will cause a round-up to the next 100th by printf( "%.2lf", x ) for n.nn5 values. without affecting the displayed value for values not n.nn5

double x2  = x * (1 + DBL_EPSILON) ; // round half-away from zero
printf( "%.2lf", x2 ) ;

对于不同的舍入行为:

double x2  = x * (1 - DBL_EPSILON) ;  // round half-toward zero
double x2  = x + DBL_EPSILON ;        // round half-up
double x2  = x - DBL_EPSILON ;        // round half-down

这篇关于在 C 中将正值四舍五入到小数点后两位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆