Manu
Manu

Reputation: 11

I don´t know why the else if statement doesn´t happen

When I input 0.50 or other floats that can be divided by 0.25 I don´t get any error but when I input 0.10 or other float that can´t be divided by 0.25 the else if statement that I have written does not happen. Can anyone tell me why?

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

int main(void) {
    float change;
    do {
        change = get_float("Change owed: ");        
    } while (change < 0.009);
    int count = 0;
    int div = 0;
    while (change > 0.00) {
        if ((change / 0.25) >= 1.00) {
            div = round(change / 0.25);
            count += div;
            change = change - (div  *0.25);
        } else
        if ((change / 0.10) >= 1.00) {
            div = round(change / 0.10);
            count += div;
            change = change - (div * 0.10);
        } else
        if ((change / 0.05) >= 1.00) {
            div = round(change / 0.05);
            count += div;
            change = change - (div * 0.05);
        } else {
            div = round(change / 0.01);
            count += div;
            change = change - (div * 0.01);
        }
    }
    printf("%i\n", count);
}

Upvotes: 1

Views: 144

Answers (1)

chqrlie
chqrlie

Reputation: 144969

The internal representation of floating point numbers C is almost always the binary formats specified in the IEEE 754 binary representations, not a decimal form. As a consequence, some numbers with a simple representation in decimal notation such as 0.1 as not represented exactly in a float or even in a double variable. Multiplying this variable by 10 does not necessarily yield the value 1 exactly, but a very close floating point number different from 1. Comparing floating point numbers should be done with extreme care, allowing for the small differences coming from the propagation of the rounding method. In particular, you should avoid using float or double for currency values where the exact number of cents matters: use an integer holding the number of cents with a large enough size to handle the computed numbers. Regular 32-bit int would not suffice for numbers greater than 20 million USD expressed in cents.

Here is a modified version using long int for at least 32-bit size:

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

int main(void) {
    float change = get_float("Change owed: ");        
    long int cents = round(change * 100); // get an exact number of cents.
    long int count = cents / 25;  // number of quarters
    cents %= 25;
    count += cents / 10;     // number of dimes
    cents %= 10;
    count += cents / 5;      // number of nickels
    cents %= 5;
    count += cents;          // number of pennies
    printf("%ld coins\n", count);
    return 0;
}

Upvotes: 6

Related Questions