问题描述
我已经写了一个C程序(这是我的项目的一部分)四舍五入一个浮点值的用户指定的精度给定。这个函数就像这样$ $ $ $ $ $ $ $ $ $ $ $ $'
我在这个程序中所做的是将浮点数转换成一个字符串,然后处理它。
但是有没有办法把这个数字保持为float本身并且实现相同。 num = 4.445 prec = 1 result = 4.4
当然有。非常简单:
#include< math.h>
float custom_round(float num,int prec)
{
int trunc = round(num * pow(10,prec));
return(float)trunc / pow(10,prec);
编辑:在我看来,你想要这个,因为你认为你可以'在格式字符串中具有动态精度。显然,你可以:
int precision = 3;
double pie = 3.14159265358979323648; //我饿了,我需要一个双馅饼
printf(Pi等于%。* lf\\\
,精度,派);
打印 3.142
。
I have written a C program (which is part of my project) to round off a float value to the given precision specified by the user. The function is something like this
float round_offf (float num, int precision)
What I have done in this program is convert the float number into a string and then processed it.
But is there a way to keep the number as float itself and implement the same.
Eg. num = 4.445 prec = 1 result = 4.4
解决方案 Of course there is. Very simple:
#include <math.h>
float custom_round(float num, int prec)
{
int trunc = round(num * pow(10, prec));
return (float)trunc / pow(10, prec);
}
Edit: it seems to me that you want this because you think you can't have dynamic precision in a format string. Apparently, you can:
int precision = 3;
double pie = 3.14159265358979323648; // I'm hungry, I need a double pie
printf("Pi equals %.*lf\n", precision, pie);
This prints 3.142
.
这篇关于在C中手动实现舍入函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!