[Solved] can someone examine the algorithm [closed]


You problem is with floating point precision.

float i = 4.2;
i *= 100;
printf("%f\n", i);

Print: 419.999969 and not 4.2 as it should, in this case 419 is the value used in the coin problem resulting in 22 coins used 16 of 25, 1 of 10, 1 of 5 and 4 of 1 = total 22

Use: i = round(i * 100); instead of i = i * 100;

You need to contemplate the equal value, eg: else if (i >= 10 && i < 25), the range is [ini, fin), close at the beginning, open at the end. If you change the else if by if you don’t need the while loop.

Final code:

#include <stdio.h>
#include <math.h>

int main() {
    int c = 0;
    float iv = 4.2;
    int i = round(iv * 100);

    printf("%d\n", i);
    if (i >= 25) {
        c += i / 25;
        i = i % 25;
    }
    if (i >= 10) {
        c += i / 10;
        i = i % 10;
    }
    if (i >= 5) {
        c += i / 5;
        i = i % 5;
    }
    if (i > 0) {
        c += i;
    }
    printf("%d\n", c);

    return 0;
}

More info about
What Every Programmer Should Know About Floating-Point Arithmetic

solved can someone examine the algorithm [closed]