简体   繁体   中英

Subtracting floats in C language

#include <stdio.h>
#include <stdlib.h>

float sum  (float *A, int len) // sum of table of floats
{
    float ss = 0.0;
    int i;

    for(i=0; i < len; ++i)
        ss +=A[i];
    return ss;
}
void print(float A[][3], int row) //// procedure that prints sum of elements for each row in 2D table
{
    int i, j;
    float k;

    for(i = 0; i < row; i++)
    {
        k=0.0;
        for(j = 0; j < 3; j++)
        {
            k=A[i][j]+k;
        }
        printf (" %2.2f  \n",  k);
    }
    return;
}
int compare(const void *p,const void *q) // sort 2D table in ascending order by sum in rows

{
    float *a = (float*)p;
    float *b = (float*)q;
    float l=sum(a,3);
    float r=sum(b,3);         // CORRECTLY WRITTEN COMPARE FUNCTION
    if (l<r) return -1;
    if (l==r) return 0;
    else return 1;
}

/* int compare(const void *p,const void *q)
{
    float *a = (float*)p;
    float *b = (float*)q;
    float l=sum(a,3);
    float r=sum(b,3);          // WRONGLY WRITTEN COMPARE FUNCTION
    return l-r;
} */

int main()
{
    float TAB_1[ ][3]= {{1.3,2.4,1.1},{4.9,5.9,0.},{5.1,5.1, 1.1},{6.1,7.0,0.3},{1.3,1.3, 3.1},
    {1.3,1.3, 0.1},{4.4,4.3, 4.1},{1.3,1.2, 3.1},{1.3,1.3, 8.1}};

    print(TAB_1,sizeof(TAB_1)/sizeof(TAB_1[0]) );
    qsort(TAB_1,sizeof(TAB_1)/sizeof(TAB_1[0]),sizeof(TAB_1[0]),compare);
    puts("");
    print(TAB_1, sizeof(TAB_1)/sizeof(TAB_1[0]));
    return 0;
}

Why commented function that I marked as WRONGLY WRITTEN COMPARE FUNCTION gives bad output? Is it a problem with float representation in C or with subtraction 2 floats? Could somebody explain?

The compare function with lr is wrong if the difference between these two numbers is less than 1 , more accurately if abs(lr) < 1 . The reason is that the result of the floating point operation lr is converted to int , and anything between 0..0.99999.. will yield 0 , just as if these two numbers were equal (even if they aren't).

The following short program illustrates this:

int main() {

    float f1 = 3.4;
    float f2 = 3.7;

    int compareResultWrong = f2 - f1;
    int compareResultOK = (f1 < f2);

    printf("result should be 1; Wrong: %d, OK: %d\n", compareResultWrong, compareResultOK);
}

Is it a problem with float representation in C or with subtraction 2 floats?

Neither first nor second - it is definitely wrong implementation.

Just look what occurs when -0.01 or 0.01 result is casted to int result of function?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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