简体   繁体   English

舍入到浮点数的源代码

[英]Source code to round floating point number

Other than using any inbuilt function like ceil and floor how can you round a floating point number? 除了使用诸如ceilfloor任何内置函数外,如何舍入浮点数?

I want to convert 2.10 to 2.14-> 2.1 and 2.15 to 2.19 -> 2.2 我想将2.10转换为2.14-> 2.1并将2.15转换为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;
    }

I tried lot of inbuild function but all that not workign for my diab compiler 我尝试了很多inbuild函数,但是对于我的diab编译器来说,所有这些都不起作用

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

planning to write my own logic 打算写自己的逻辑

float a = 2.24;
float b = roundf(a*10.0f)/10.0f;//roundf in C99

Try int((x + 0.05) * 10.0) / 10.0 . 尝试int((x + 0.05) * 10.0) / 10.0

You can also use trunc instead of the conversion to and from int . 您也可以使用trunc代替int的转换。

Or you could use round : round(x * 10.0) / 10.0 或者您可以使用roundround(x * 10.0) / 10.0

If you just want to round the number for output purposes, then the %.1f format string is indeed the correct answer. 如果您只想四舍五入以用于输出目的,那么%.1f格式字符串确实是正确的答案。

printf("%.1f", 2.14);

or If you actually want to round off value then something like this work 或者,如果您实际上想舍入价值,那么类似的工作

#include <math.h>

float val = 37.777779;

float rounded_down = floorf(val * 100) / 100;   /* Result: 37.77 */
float nearest = floorf(val * 100 + 0.5) / 100;  /* Result: 37.78 */
float rounded_up = ceilf(val * 100) / 100;      /* Result: 37.78 */

Usually we use nearest method 通常我们使用nearest方法

BLUEPIXY's answer is good. BLUEPIXY的答案很好。 But in general; 但总的来说; floating point multiplication is faster than division, so if speed is relevant; 浮点乘法比除法快,所以如果速度合适的话; multiply by 0.1 instead of dividing by 10. 乘以0.1,而不是除以10。

Because my old answer needs lot of careful programming to make it work 因为我的旧答案需要很多仔细的编程才能使其起作用

I present another way to implement an round function: 我提出了另一种实现舍入功能的方法:

You can easily check if a (positive/negative) number will be rounded up or down by (adding/subtracting) 0.5. 您可以轻松地检查(正/负)数字是否被向上或向下四舍五入(加/减)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;
}

And here you can see a working example. 在这里,您可以看到一个有效的示例。

Old one: 旧的:

You can use sprint: 您可以使用sprint:

#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);
}

You can see the logic. 您可以看到逻辑。 Finally you can revert the string to integer and multiply by 100. 最后,您可以将字符串还原为整数并乘以100。

EDIT: It's only the logic. 编辑:这只是逻辑。 See comments below for what is needed to fully work. 请参阅下面的评论,以了解充分工作所需的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM