计算CS50锻炼的硬币难度

时间:2018-11-25 11:02:34

标签: c cs50

下面是我的零钱机器代码。我使用贪婪算法来找出用于找零的正确硬币数量。

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

 int main(void)
{
    float user_money = get_float("How many dollars: ");
    printf("\n");
    float cost_item = get_float("Cost of item: ");
    printf("\n");
    float user_change = user_money - cost_item;
    float coin_change = user_money - cost_item;
    int coins = 0;
    while(true)
    {
        if(coin_change >= .25)
        {
            coins += 1;
            coin_change = coin_change - .25;
            continue;
        }
        else if(coin_change >= .10)
        {
            coins += 1;
            coin_change = coin_change - .10;
            continue;
        }
        else if(coin_change >= .05)
        {
            coins += 1;
            coin_change = coin_change - .05;
            continue;
        }
        else if(coin_change >= .01)
        {
            coins += 1;
            coin_change = coin_change - .01;
            continue;
        }
        else
        {
             break;
        }
    }
    printf("Change: %f", user_change);
    printf("\n");
    printf("coins: %d", coins);
    printf("\n");
}

问题:

user_money = 10

count_item = 9.73

终端:

更改:.27

硬币:3

正确

但是

user_money = 10

count_item = 9.72

终端:

更改:.28

硬币:3 //这应该是4个硬币(1个Q 3便士)

除非我在脑子里加错了。

1 个答案:

答案 0 :(得分:-5)

我找到了自己的答案:

HHOOK hook = NULL;

BOOL WINAPI ctrl_handler(DWORD dwCtrlType)
{
    if (hook) {
        std::cout << "Unhooking " << hook << '\n';
        UnhookWindowsHookEx(hook);
        hook = NULL;  // ctrl_handler might be called multiple times
        std::cout << "Bye :(";
        std::cin.get();  // gives the user 5 seconds to read our last output
    }

    return TRUE;
}

int main()
{
    SetConsoleCtrlHandler(ctrl_handler, TRUE);
    hook = SetWindowsHookExW(WH_MOUSE_LL, MouseHookProc, nullptr, 0);

    if (!hook) {
        std::cerr << "SetWindowsHookExW() failed. Bye :(\n\n";
        return EXIT_FAILURE;
    }

    std::cout << "Hook set: " << hook << '\n';
    GetMessageW(nullptr, nullptr, 0, 0);
}

我将coin_change的值从.01更改为.00,以便计算机可以识别它仍然可以减去coin_change并添加到硬币中。在尝试调试自己的答案时,我还添加了一些其他功能。