c浮点数怎么四舍五入

#include <stdio.h> /* printf */

#include <math.h>       /* round, floor, ceil, trunc */

inline int myIntRound(double dInput)
{
    if(dInput >= 0.0f)
    {
        return ((int)(dInput + 0.5f));
    }
    return ((int)(dInput - 0.5f));
}

double d[]={-1.5, -0.7, -0.5, -0.3, 0.3, 0.5, 0.7, 1.5, 1.9};

int print_doubles(double d[], int n)
{
    printf("original\n");
    for(int i=0;i<n;i++)
        printf (" %f", d[i]);
    printf("\n");
}

//直接int会舍弃浮点部分,只取整数
int print_int_doubles(double d[], int n)
{
    printf("int\n");
    for(int i=0;i<n;i++)
        printf (" %f", double(int(d[i])));
    printf("\n");
}

int print_round_doubles(double d[], int n)
{
    printf("round\n");
    for(int i=0;i<n;i++)
        printf (" %f", round(d[i]));
    printf("\n");
    for(int i=0;i<n;i++)
        printf (" %d", int(round(d[i])));
    printf("\n");
}

int print_ceil_doubles(double d[], int n)
{
    printf("ceil\n");
    for(int i=0;i<n;i++)
        printf (" %f", ceil(d[i]));
    printf("\n");
}
int print_floor_doubles(double d[], int n)
{
    printf("floor\n");
    for(int i=0;i<n;i++)
        printf (" %f", floor(d[i]));
    printf("\n");
}

int print_trunc_doubles(double d[], int n)
{
    printf("trunc\n");
    for(int i=0;i<n;i++)
        printf (" %f", trunc(d[i]));
    printf("\n");
}

//和round
int print_myint_doubles(double d[], int n)
{
    printf("myint\n");
    for(int i=0;i<n;i++)
        printf (" %d", myIntRound(d[i]));
    printf("\n");
}


int main ()
{
    print_doubles(d, sizeof(d)/sizeof(d[0]));
    print_int_doubles(d, sizeof(d)/sizeof(d[0]));
    print_round_doubles(d, sizeof(d)/sizeof(d[0]));
    print_floor_doubles(d, sizeof(d)/sizeof(d[0]));
    print_ceil_doubles(d, sizeof(d)/sizeof(d[0]));
    print_trunc_doubles(d, sizeof(d)/sizeof(d[0]));
    print_myint_doubles(d, sizeof(d)/sizeof(d[0]));
    return 0;
}

/*
:! ./round
original
 -1.500000 -0.700000 -0.500000 -0.300000 0.300000 0.500000 0.700000 1.500000 1.900000
int
 -1.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 1.000000 1.000000
round
 -2.000000 -1.000000 -1.000000 -0.000000 0.000000 1.000000 1.000000 2.000000 2.000000
 -2 -1 -1 0 0 1 1 2 2
floor
 -2.000000 -1.000000 -1.000000 -1.000000 0.000000 0.000000 0.000000 1.000000 1.000000
ceil
 -1.000000 -0.000000 -0.000000 -0.000000 1.000000 1.000000 1.000000 2.000000 2.000000
trunc
 -1.000000 -0.000000 -0.000000 -0.000000 0.000000 0.000000 0.000000 1.000000 1.000000
myint
 -2 -1 -1 0 0 1 1 2 2


 */

测试后可以发现,直接int转换不行,会丢失浮点部分。 要用+0.5或-0.5方式。 或者用round函数

posted on 2020-05-27 15:51  zhezhelin  阅读(...)  评论(...编辑  收藏

统计