是否有一个函数圆在C浮动或我需要写我自己?
-
20-08-2019 - |
题
有圆在C浮动或我需要写我自己的函数吗?
浮CONVER = 45的 59 强> 2346543;
我想实际值四舍五入至小数点后一位,CONVER = 45的 6 强>
解决方案
作为罗布提到的,你可能只是想的打印的浮子1位小数。在这种情况下,你可以做一些这样的:
#include <stdio.h>
#include <stdlib.h>
int main()
{
float conver = 45.592346543;
printf("conver is %0.1f\n",conver);
return 0;
}
如果你想真正全面的存储值,这是一个更复杂一点。首先,你的一位小数就地表示将很少有浮点精确的模拟。如果你只是想尽可能接近,这样的事情可能做的伎俩:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
float conver = 45.592346543;
printf("conver is %0.1f\n",conver);
conver = conver*10.0f;
conver = (conver > (floor(conver)+0.5f)) ? ceil(conver) : floor(conver);
conver = conver/10.0f;
//If you're using C99 or better, rather than ANSI C/C89/C90, the following will also work.
//conver = roundf(conver*10.0f)/10.0f;
printf("conver is now %f\n",conver);
return 0;
}
我怀疑这第二个例子就是你要找的东西,但我把它的完整性。如果你确实需要用这种方式代表你的号码在内部,而不仅仅是输出,可以考虑使用定点点表示的代替。
其他提示
当然,你可以使用 roundf()的。如果你想圆到小数点后一位,那么你可以这样做:roundf(10 * x) / 10
#include <math.h>
double round(double x);
float roundf(float x);
不要忘了用-lm链接。还参见ceil(),地板()和TRUNC()。
只是为了推广罗布的回答一点,如果你的不的做输出,仍然可以使用相同的接口与sprintf()
。
我觉得有另一种方式来做到这一点,虽然。您可以尝试ceil()
和floor()
围捕和向下。一个好的技巧是添加0.5,所以任何超过0.5回合了,但在它之下的任何几轮下来。 ceil()
和floor()
仅在double
s工作虽然。
编辑:另外,对于浮体,则可以使用truncf()
截断浮动。相同的0.5特技应该工作做精确舍入。
有一个round()
功能,也fround()
,这将舍入到最接近的整数表示为两倍。但是,这是不是你想要的。
我有同样的问题,并写了这个:
#include <math.h>
double db_round(double value, int nsig)
/* ===============
**
** Rounds double <value> to <nsig> significant figures. Always rounds
** away from zero, so -2.6 to 1 sig fig will become -3.0.
**
** <nsig> should be in the range 1 - 15
*/
{
double a, b;
long long i;
int neg = 0;
if(!value) return value;
if(value < 0.0)
{
value = -value;
neg = 1;
}
i = nsig - log10(value);
if(i) a = pow(10.0, (double)i);
else a = 1.0;
b = value * a;
i = b + 0.5;
value = i / a;
return neg ? -value : value;
}
要打印圆形值, @马特Ĵ以及回答了这个问题。
float x = 45.592346543;
printf("%0.1f\n", x); // 45.6
由于大部分浮点(FP)是二进制基于确切四舍五入到一个小数地方时在数学上正确的答案是不可能x.1, x.2, ...
。
要的FP数字转换到最接近 0.1
是另一回事。
<强>溢出强>:途径由10(或100,1000,等)第一刻度可能会溢出对于大x
float round_tenth1(float x) {
x = x * 10.0f;
...
}
<强>双舍入强>:添加0.5F,然后使用floorf(x*10.0f + 0.5f)/10.0
当中间总和x*10.0f + 0.5f
向上舍入到一个新的整数返回错误结果
// Fails to round 838860.4375 correctly, comes up with 838860.5
// 0.4499999880790710449 fails as it rounds to 0.5
float round_tenth2(float x) {
if (x < 0.0) {
return ceilf(x*10.0f + 0.5f)/10.0f;
}
return floorf(x*10.0f + 0.5f)/10.0f;
}
<强>铸造以int
当float x
比INT_MAX
大得多具有明显的问题。
在roundf()
使用<math.h>
和家庭,购是最好的办法。
float round_tenthA(float x) {
double x10 = 10.0 * x;
return (float) (round(x10)/10.0);
}
要避免使用double
,简单地,如果数字四舍五入需要测试。
float round_tenthB(float x) {
const float limit = 1.0/FLT_EPSILON;
if (fabsf(x) < limit) {
return roundf(x*10.0f)/10.0f;
}
return x;
}
可以使用的#define轮(A)(int)的(A + 0.5)作为宏 所以每当你写轮(1.6),它返回2和每当你写轮(1.3)将其返回1。