可能是重复问题:
在C语言中将数字保留两位小数
我在c语言中没有找到像这里这样带有签名double round(double d, int digits)
的函数。
当我尝试构建时,会出现以下错误:
错误:函数'round'的参数太多
如何在C语言中保留N位小数进行四舍五入?
可能是重复问题:
在C语言中将数字保留两位小数
我在c语言中没有找到像这里这样带有签名double round(double d, int digits)
的函数。
当我尝试构建时,会出现以下错误:
错误:函数'round'的参数太多
如何在C语言中保留N位小数进行四舍五入?
使用递归(某些位数的值会变慢)
#include <math.h>
double my_round(double x, unsigned int digits) {
if (digits > 0) {
return my_round(x*10.0, digits-1)/10.0;
}
else {
return round(x);
}
}
一种可能会更快的方法,但是它依赖于对缓慢的pow
函数的单个调用:
#include <math.h>
double my_round(double x, unsigned int digits) {
double fac = pow(10, digits);
return round(x*fac)/fac;
}
pow
。#include <math.h>
double fac[]; // population of this is left as an exercise for the reader
double my_round(double x, unsigned int digits) {
return round(x*fac[digits])/fac[digits];
}
round
有两个不同的调用签名,从而导致类型冲突。 - DSM虽然“answerd”给出了一个不错的答案,但这里有一个适用于任意大数的解决方案:
double round1(double num, int N) {
ASSERT(N > 0);
double p10 = pow(10,N);
return round(num* p10) / p10;
}
printf("%8.5f", round1(3.7519, 1));
,则不能保证它会打印为3.70000。这是与IT相关的内容。这是一个(非常)简单的函数,
double round1(double num, int N) {
int temp=(int) num*pow(10,N);
double roundedN= temp/pow(10,N);
return roundedN;
}
pow
是一项昂贵的操作,请存储结果而不是两次调用它。 - Henrypow
函数可以高效地实现(具有O(log n)的复杂度)。因此在这种情况下它是很便宜的。 - Artem Sobolev在C标准中,这样的函数并不存在。不过,你可以自己编写一个。
#include <math.h>
/* Round `n` with `c` digits after decimal point. */
double nround (double n, unsigned int c)
{
double marge = pow (10, c);
double up = n * marge;
double ret = round (up) / marge;
return ret;
}
请参考上面关于浮点数“小数点”的评论。