如何在C中四舍五入浮点值(如37.777779)到小数点后两位(37.78)?
当前回答
...或者你也可以采用传统的方式,不需要任何库:
float a = 37.777779;
int b = a; // b = 37
float c = a - b; // c = 0.777779
c *= 100; // c = 77.777863
int d = c; // d = 77;
a = b + d / (float)100; // a = 37.770000;
当然,如果你想从数字中去除额外的信息。
其他回答
在c++中(或在带有C风格强制类型转换的C中),您可以创建以下函数:
/* Function to control # of decimal places to be output for x */
double showDecimals(const double& x, const int& numDecimals) {
int y=x;
double z=x-y;
double m=pow(10,numDecimals);
double q=z*m;
double r=round(q);
return static_cast<double>(y)+(1.0/m)*r;
}
然后std::cout << showDecimals(37.777779,2);结果是:37.78。
显然,你不需要在函数中创建所有5个变量,但我把它们留在那里,这样你就可以看到逻辑。可能有更简单的解决方案,但这对我来说很有效——特别是因为它允许我根据需要调整小数点后的位数。
你仍然可以使用:
float ceilf(float x); // don't forget #include <math.h> and link with -lm.
例子:
float valueToRound = 37.777779;
float roundedValue = ceilf(valueToRound * 100) / 100;
double f_round(double dval, int n)
{
char l_fmtp[32], l_buf[64];
char *p_str;
sprintf (l_fmtp, "%%.%df", n);
if (dval>=0)
sprintf (l_buf, l_fmtp, dval);
else
sprintf (l_buf, l_fmtp, dval);
return ((double)strtod(l_buf, &p_str));
}
这里n是小数的个数
例子:
double d = 100.23456;
printf("%f", f_round(d, 4));// result: 100.2346
printf("%f", f_round(d, 2));// result: 100.23
使用%。printf中的2f。它只打印2个小数点。
例子:
printf("%.2f", 37.777779);
输出:
37.77
这个宏用于浮点数四舍五入。 把它添加到你的头文件中
#define ROUNDF(f, c) (((float)((int)((f) * (c))) / (c)))
这里有一个例子:
float x = ROUNDF(3.141592, 100)
X = 3.14:)
推荐文章
- 在C和c++中静态变量存储在哪里?
- errno线程安全吗?
- 如何在C程序中获取当前目录?
- 互斥实例/教程?
- 如何添加一个'或'条件在#ifdef
- extern关键字对C函数的影响
- 如果使用if-return-return或if-else-return?
- 用于双值的assertEquals的delta或epsilon参数的含义
- 转换Python程序到C/ c++代码?
- 为什么程序不是经常用汇编编写的?
- 有没有替换Windows (Visual C)的unistd.h ?
- 使用gcc命令行从.c文件构建.so文件
- C多行宏:do/while(0) vs作用域块
- time_t最终的类型定义是什么?
- 我需要显式处理负数或零时,总和平方数字?