首页 > 解决方案 > 最少的硬币数量

问题描述

请找到问题上下文如下:

编写一个程序,接受一个表示金额的浮点值,例如 2.8 表示 2 美元和 80 美分。然后程序应显示偿还硬币金额所需的最小硬币数量。假设用户输入的值大于 0 小于 10。

#include <stdio.h>

int main(void) {
    double amt;
    printf("Enter amount:");
    scanf("%lf", &amt);

    int amt_cents;
    amt_cents = amt * 100;

    int dollar_1;
    dollar_1 = amt_cents / 100;
    amt_cents = amt_cents - (dollar_1 * 100);

    int cents_50;
    cents_50 = amt_cents / 50;
    amt_cents = amt_cents - (cents_50 * 50);

    int cents_20;
    cents_20 = amt_cents / 20;
    amt_cents = amt_cents - (cents_20 * 20);

    int cents_10;
    cents_10 = amt_cents / 10;
    amt_cents = amt_cents - (cents_10 * 10);

    int cents_05;
    cents_05 = amt_cents / 5;
    amt_cents = amt_cents - (cents_05 * 5);

    int cents_01;
    cents_01 = amt_cents / 1;
    amt_cents = amt_cents - (cents_01 * 1);

    if (dollar_1 != 0) {
        printf("Number of 1$: %d\n", dollar_1);
    }
    if (cents_50 != 0) {
        printf("Number of 50c: %d\n", cents_50);
    }
    if (cents_20 != 0) {
        printf("Number of 20c: %d\n", cents_20);
    }
    if (cents_10 != 0) {
        printf("Number of 10c: %d\n", cents_10);
    }
    if (cents_05 != 0) {
        printf("Number of 5c: %d\n", cents_05);
    }
    if (cents_01 != 0) {
        printf("Number of 1c: %d\n", cents_01);
    }
}

输出:

输入金额:1.1 1$ 的数量:1 10c 的数量:1

输入金额:2.1 1$ 的数量:2 10c 的数量:1

输入金额:3.1 1$ 的数量:3 10c 的数量:1

输入金额:4.1 1$ 的数量:4 5c 的数量:1 1c 的数量:4

输入金额:5.1 1$ 的数量:5 5c 的数量:1 1c 的数量:4

输入金额:6.1 1$ 的数量:6 10c 的数量:1

问题: 为什么 4.1 和 5.1 的值与 0 - 10 范围内的所有其他值的工作方式不同?通过手动计算代码,似乎 4.1 和 5.1 应该与所有其他情况一致,仅为 10c 生成值 1,但在执行程序时情况并非如此。

标签: cfloating-pointcoin-change

解决方案


为什么 4.1 和 5.1 的值与 0 - 10 范围内的所有其他值的工作方式不同?

因为浮点数并不总是准确地表示值。看看这段代码:

double amt;
printf("Enter amount:");
scanf("%lf", &amt);

int amt_cents;
amt_cents = amt * 100;

如果您在最后一行之后设置断点并检查您的值,amt_cents您可能会发现它409不是410您所期望的,因为amt类似于4.09999999....

您需要将数字四舍五入到最接近的整数,而不是只取整数部分,一种简单的方法是在值上加上 0.5,然后截断:

amt_cents = amt * 100.0 + 0.5;

推荐阅读