-3
#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?

OmG
  • 18,337
  • 10
  • 57
  • 90
pooo mn
  • 23
  • 1
  • 6

2 Answers2

1

The compare function with l-r is wrong if the difference between these two numbers is less than 1, more accurately if abs(l-r) < 1. The reason is that the result of the floating point operation l-r 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);
}
Stephan Lechner
  • 34,891
  • 4
  • 35
  • 58
0

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?

MBo
  • 77,366
  • 5
  • 53
  • 86