且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在“ C”中的贪婪算法被称为“ C”。

更新时间:2021-10-06 00:00:38

关于代码:


  • 您在第一个循环中使用 cents 时, code> amount_left ,在第一个循环中,如果需要多次迭代,则结果将是不正确的。

  • 建议更好将 amount_left-10> = 0 更改为 amount_left> = 10

  • 最后一个 printf 语句最有可能(按文字显示)用于打印通过提供的金额获得的硬币数量。

  • You are using in the first loop cents when there would be amount_left, in the case of the first loop if it require more that one iteration, the result would be incorrect.
  • As recommended is better to change amount_left - 10 >= 0 by amount_left >= 10.
  • The final printf statement most probably (by the text) is for printing the count of coin gained by the amount provided.

代码:

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

int main(void) {
    float amount = 0;
    int cents = 0;
    int count = 0;
    int amount_left = 0;

    amount = .30;

    cents = (int)round(amount * 100);

    printf("%d\n", cents);

    amount_left = cents;

    while (amount_left >= 25) {
        count++;
        amount_left -= 25;
    }
    while (amount_left >= 10) {
        count++;
        amount_left -= 10;
    }
    while (amount_left >= 5) {
        count++;
        amount_left -= 5;
    }
    while (amount_left >= 1) {
        count = count + 1;
        amount_left -= 1;
    }
    printf("You get %d coins\n", count);
}

使用公式: initial_amount = 硬币价值 * 已使用硬币 + amount_left

Using the formula: initial_amount = coin value * coin used + amount_left

这可以用C写成:


  • initial_amount / 硬币价值 = 已使用硬币

  • 初始金额硬币价值 = amount_left

  • initial_amount / coin value = coin used
  • initial_amount % coin value = amount_left

更优化的解决方案:

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

int main(void) {
    float amount = 0;
    int cents = 0;
    int count = 0;
    int amount_left = 0;

    amount = .30;

    cents = (int)round(amount * 100);

    printf("%d\n", cents);

    amount_left = cents;          // beginning with 30 cents

    count += amount_left / 25;    // 30 / 25 = 1,      one 25 cent coin
    amount_left %= 25;            // 30 % 25 = 5,      left with 5 cents

    count += amount_left / 10;    // 5 / 10 = 0        no coin used
    amount_left %= 10;            // 5 % 10 = 5        left the same 5 cents

    count += amount_left / 5;     // 5 / 5 = 1         one 5 cent coin
    amount_left %= 5;             // 5 % 5 = 0         left with 0 cents

    count += amount_left;        // not needed 1 cent coins.

    printf("You get %d coins\n", count);
}

注意:


  • 不需要 while循环操作 17/5 = 3 用整数运算在 C 17%5 = 2 中。

  • 使用此功能对于价值 N 的硬币,数量/ N 硬币计数(可以为0,例如: amount = 9 N = 10 9/10 = 0 ),剩余的金额为金额%​​N

  • 最后一种情况(对于1的硬币)始终为 amount = 0

  • There is no need to while loop operation 17 / 5 = 3 in integers arithmetic in C and 17 % 5 = 2.
  • Using this you use for a coin of value N, amount / N coins count (could be 0, eg: amount = 9 and N = 10, 9/10 = 0 in integer division) and the amount left is amount % N.
  • The last case (for coin of 1) always left amount = 0.