3 May 2017

CS50. Greedy

My code can be optimized, however, for better understanding, I left it as is.

/**
 * CS50: Greedy
 * Aleksey M.
 * 29.04.17
 *
 */

// Compile: clang -o greedy greedy.c -lcs50
// Run: ./greedy
// Check cs50: check50 2014.fall.pset1.greedy greedy.c
// Check cs50 style: style50 <fileName>.c

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

#define QUARTER 25
#define DIME    10
#define NICKEL  5
// #define PENNY   1

int main(void)
{

    float cash;
    int cents;
    int countQuarter;
    int countDime;
    int countNickel;
    int countPenny;
    int sum;
    int balance;

    // Prompt user to set value
    do
    {
        printf("Hello! How much change do you have for me?: $");
        cash = GetFloat();

    } while (cash < 0);

    // Debug!
    // printf("Yep! %0.50f \n", cash);

    // Convert dollars to cents
    cash *= 100;

    // Round the value and casting the "double" type of round() to "int"
    cents = (int) round(cash);

    // Check quarters
    countQuarter = cents / QUARTER;
    balance = cents % QUARTER;

    // Check dimes
    countDime = balance / DIME;
    balance = balance % DIME;

    // Check nickels
    countNickel = balance / NICKEL;
    balance = balance % NICKEL;

    // Check pennies
    countPenny = balance;

    // Sum
    sum = countQuarter + countPenny + countNickel + countDime;
    printf("%d\n", sum);

    return 0;
}
  

No comments:

Post a Comment

Popular Posts