c - 在 C 中手动实现舍入函数

标签 c floating-point rounding

我编写了一个 C 程序(这是我项目的一部分)来将浮点值四舍五入到用户指定的给定精度。函数是这样的

     float round_offf (float num, int precision)

我在这个程序中所做的是将 float 转换为字符串,然后对其进行处理。

但是有没有办法让数字本身保持 float 并实现相同。

例如。 num = 4.445 prec = 1 结果 = 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; // I'm hungry, I need a double pie
printf("Pi equals %.*lf\n", precision, pie);

这会打印 3.142

关于c - 在 C 中手动实现舍入函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12525891/

相关文章:

c - 如何每四个循环以及每隔一个循环做一些事情?

c - 编写质因数分解程序 C

math - 为什么十进制数不能用二进制精确表示?

c# - C# 中的舍入函数

在 C 问题中创建多个线程

lua - 如果 lua number 是 double,=/<=/>= 操作总是正确的吗?

floating-point - WebGL渲染为浮点纹理

python - 如何用 tensorflow 准确地四舍五入

c - 显示 Float 6 位小数,带 2 位小数舍入

c - Scanf 未知数的整数