-2

I wrote this code:

float suma;
int centy;
int cele;
printf("Zadaj sumu a ja ti ju napisem a zaroven aj vysklonujem:\n");
scanf("%f",&suma);
cele=(int)suma;
centy= (suma-cele)*100;

switch ((int)suma) {
    case 1:
        printf("%d euro",(int)suma);
        break;
    case 2 ... 4:
        printf("%d eura",(int)suma);
        break;

    default:
        printf("%d eur",(int)suma);
        break;

}
switch (centy) {
    case 1:
        printf(" a %d cent\n",centy);
        break;
    case 2 ... 4:
        printf(" a %d centy\n",centy);
        break;

    default:
        printf(" a %d centov\n",centy);
        break;
}

But when I type 5.56 it will say that I have typed 5.55 in console. What do you think. What should I change? I am newbie so...

RA3SK
  • 11
  • 6

1 Answers1

1

You have to correct for rounding errors when using floating point numbers. An easy way that often works is to add 0.5 before converting to an int. So, something like this should work better:

centy= (int) (0.5 + suma * 100.0) - cele * 100;

It's probably better to read the input as a string and parse it into euros and cents using the '.' as a delimiter. But this will get the code working easily. Adding 0.5 often works when you don't need exact precision, but close enough will do.

bruceg
  • 2,433
  • 1
  • 22
  • 29