首页 > 解决方案 > C _cashier 中的贪心算法

问题描述

我目前正在参加哈佛的 CS50 - Introduction to cs,我之前没有任何编码经验。所以我有点难以完成作业。

我的代码的主要目的是计算用于给定数量现金的最小硬币数量(25、10、5 和 1)。此外,我必须将美元兑换成美分。这是我的代码:

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

int main (void)
{

int change = 0;

 float dollars = get_float("Change: ");
 int cents = round( dollars * 100);  

while ( 0 > dollars ) 
; 
   
{
    if ( cents >= 25)
    {
        cents = cents - 25;
        change++;
    }
    else if ( cents >= 10)
    {
        cents = cents - 10;
        change ++;
    }
    else if ( cents >= 5)
    {
        cents = cents - 5;
        change++;
    }
    else if ( cents >= 1)
    {
        cents = cents - 1;
        change++;
    }
    printf("%i\n" , change);
}
}

不幸的是,我找不到错误在哪里。当我输入“5”时,它给了我数字“1”但是,当我输入 0.25 时,它也给了我结果“1”。任何人都可以帮忙吗?

标签: ccs50greedy

解决方案


推荐阅读