四舍五入浮点数的源代码 [英] Source code to round floating point number

查看:23
本文介绍了四舍五入浮点数的源代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

除了使用诸如 ceilfloor 之类的任何内置函数之外,您还如何舍入浮点数?

Other than using any inbuilt function like ceil and floor how can you round a floating point number?

我想将 2.10 转换为 2.14-> 2.1 和 2.15 到 2.19 -> 2.2

I want to convert 2.10 to 2.14-> 2.1 and 2.15 to 2.19 -> 2.2

我写了一些逻辑但卡在中间

I wrote some logic but stuck in the middle

    float a = 2.24;
    int b = a*100;
    int result n, i =0;
    while(i>2)
    {
        n = b%10;
        i++;
    }
    if(n >5)
    {
      c = b%10;
      c = c/10 + 1;
    }

我尝试了很多内置函数,但所有这些都不适用于我的 diab 编译器

I tried lot of inbuild function but all that not workign for my diab compiler

//  totalDist = roundf(totalDist * 10) / 10.0;      
//  totalDist = floor(totalDist * pow(10., 1) + .5) / pow(10., 1);  
    totalDist = floorf(totalDist * 10 + 0.5) / 10;

打算自己写逻辑

推荐答案

因为我的旧答案需要大量仔细的编程才能使其工作

Because my old answer needs lot of careful programming to make it work

您可以轻松检查(正/负)数字是否会四舍五入或下降(加/减)0.5.然后你可以截断结果并接受你的回答.此外,为了支持更深层次的回合您希望您可以让用户指定舍入的小数位数想要的,瞧:

You can easily check if a (positive/negative) number will be rounded up or down by (adding/subtracting) 0.5. Then you can truncate the result and take your answer. Also, in order to support deeper level of round as you want you can let the user specify how many decimal places of round the want, and voila:

long double round_f(long double number, int decimal_places)
{
     assert(decimal_places > 0);

     double power = pow(10, decimal_places-1);
     number *= power;

     return (number >= 0) ? ((long long)(number + 0.5))/power : ((long long)(number - 0.5))/power;
}

在这里您可以看到一个工作示例.

您可以使用冲刺:

#include <stdio.h>

int main(void)
{
    float a = 2.24;
    int size;
    char num[8] = {0};
    sprintf(num, "%d", (int) (a * 100));

    for (size=0; num[size]; size++);

    size--;

    if (num[size] < '5') {
        num[size] = '0';
    } else {
        num[size] = '0';
        if (num[size-1] == '9')
            num[size-1] = '0';
        else
            num[size-1]++;
    }

    printf("a = %f\n", a);
    printf("num = %s\n", num);

    return(0);
}

你可以看到逻辑.最后,您可以将字符串恢复为整数并乘以 100.

You can see the logic. Finally you can revert the string to integer and multiply by 100.

这只是逻辑.请参阅下面的评论,了解完全工作所需的条件.

It's only the logic. See comments below for what is needed to fully work.

这篇关于四舍五入浮点数的源代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆