是否有一个函数来圆在C浮动或我需要写我自己? [英] Is there a function to round a float in C or do I need to write my own?
问题描述
有圆在C浮动或我需要写我自己的函数吗?
Is there a function to round a float in C or do I need to write my own?
浮动CONVER = 45. 59 2346543;
float conver = 45.592346543;
我想实际值四舍五入至小数点后一位,CONVER = 45. 6
I would like to round the actual value to one decimal place, conver = 45.6.
推荐答案
作为罗布提到的,你可能只是想的打印的浮子1位小数。在这种情况下,你可以做类似如下:
As Rob mentioned, you probably just want to print the float to 1 decimal place. In this case, you can do something like the following:
#include <stdio.h>
#include <stdlib.h>
int main()
{
float conver = 45.592346543;
printf("conver is %0.1f\n",conver);
return 0;
}
如果您想实际一轮存储的值,这是一个稍微复杂一点。首先,你的一位小数就地重新presentation很少有浮点精确的模拟。如果你只是想获得尽可能接近,这样的事情可能做的伎俩:
If you want to actually round the stored value, that's a little more complicated. For one, your one-decimal-place representation will rarely have an exact analog in floating-point. If you just want to get as close as possible, something like this might do the trick:
#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;
}
我怀疑这第二个例子是你在找什么,但我把它的完整性。如果您确实需要重新$ P $这样psenting你的号码在内部,而不是仅仅输出,可以考虑使用定点再presentation 代替。
这篇关于是否有一个函数来圆在C浮动或我需要写我自己?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!