0

The following c code should compare float eur to an array a[k]. If I set eur = 0.05, 0.5, 5, 50, 500 the compiler finds the match. for any other value (e.g. 2, 10, 0.02) it does not find the match. The output picture is attached to this post.

1.) How come that the value in the marked line is not matched?

2.) Where do those odd values come from? actually they are expected to behave like shown in "a[3] = 10"

 int pruef(float eur)
    {
    int i, j=0, k, l=15;
    float n, z, a[l];

    for(i=0; i < 3; i++)
{   
    switch (i){
    case 0: z=0.01; break;
    case 1: z=0.02; break;
    case 2: z=0.05; break;
    }
    for(n=z; n < 501; n*=10){
    a[j] = n;
    j++;    
}
}

    for (k=0; k<l;k++)
    {
    printf("\na[%d]: %4.2f", k, a[k]);
    }


    for(k=0; k<l; k++)
    {
        printf ("\n 'eur' %f == %f array[k]", eur, a[k]);
        if (eur == a[k]) return 1;
        else continue;
    }
    return 0;

}

Here is the output:

2

a[0]: 0.01
a[1]: 0.10
a[2]: 1.00
a[3]: 10.00
a[4]: 100.00
a[5]: 0.02
a[6]: 0.20
a[7]: 2.00
a[8]: 20.00
a[9]: 200.00
a[10]: 0.05
a[11]: 0.50
a[12]: 5.00
a[13]: 50.00
a[14]: 500.00
 'eur' 2.000000 == 0.010000 array[k]
 'eur' 2.000000 == 0.100000 array[k]
 'eur' 2.000000 == 1.000000 array[k]
 'eur' 2.000000 == 9.999999 array[k]
 'eur' 2.000000 == 99.999992 array[k]
 'eur' 2.000000 == 0.020000 array[k]
 **'eur' 2.000000 == 0.200000 array[k]**
 'eur' 2.000000 == 2.000000 array[k]
 'eur' 2.000000 == 19.999998 array[k]
 'eur' 2.000000 == 199.999985 array[k]
 'eur' 2.000000 == 0.050000 array[k]
 'eur' 2.000000 == 0.500000 array[k]
 'eur' 2.000000 == 5.000000 array[k]
 'eur' 2.000000 == 50.000000 array[k]
 'eur' 2.000000 == 500.000000 array[k]
zahl nicht vorhanden

------------------
(program exited with code: 0)
Press return to continue
  • 1
    Obligatory link: http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html – sje397 Feb 16 '15 at 18:11
  • 1
    You should never do direct comparisons between floating point numbers. See https://ece.uwaterloo.ca/~dwharder/NumericalAnalysis/02Numerics/Double/paper.pdf – Bryan Oakley Feb 16 '15 at 18:12
  • @BryanOakley: There's an exception for every rule... – Deduplicator Feb 16 '15 at 18:16
  • 2
    @Deduplicator: True, but if you're asking this sort of question you should treat this rule as absolute. It's definitely one of the rules that you shouldn't break until you fully understand why you shouldn't break it. Once you reach that understanding, you'll know when you can and can't break it. – Bryan Oakley Feb 16 '15 at 18:28
  • FYI, assuming your libc supports it, you can get the exact value of a floating point number by using `printf`'s `%a` conversion specifier. In the example above `eur` is represented as `0x0x1p+1` and `a[7]` is `0x1.fffffep+0`, which explains why they are not equal. – Tim Feb 18 '15 at 22:58

0 Answers0