简体   繁体   English

“ C”中的贪婪算法

[英]Greedy Algorithm in “C”

I'm just start learning C language . 我刚刚开始学习C language I wrote this C code to implement Greedy algorithm I don't know what mistake I've made with this code, that code seems fine but its not working as I expected. 我编写了此C代码以实现Greedy算法,但我不知道我对该代码犯了什么错误,该代码看起来不错,但无法正常工作。 Can anybody help me to fix this code? 有人可以帮我修复此代码吗?

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", cents);

    amount_left = cents;

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

Notes about the problems in the code: 有关代码中问题的注释:

  • 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. 您正在使用在第一循环cents什么时候就amount_left中,如果需要更多的是一个迭代的第一个循环的情况下,结果是不正确的。
  • As recommended is better to change amount_left - 10 >= 0 by amount_left >= 10 . 如建议的那样,最好将amount_left - 10 >= 0更改为amount_left >= 10
  • The final printf statement most probably (by the text) is for printing the count of coin gained by the amount provided. 最后的printf语句很可能(按文本)是用于打印通过提供的数量获得的硬币数量。

Code: 码:

#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);
}

Using the formula: initial_amount = coin value * coin used + amount_left 使用公式: initial_amount = coin value * coin used + amount_left

This could be write in C as: 可以用C编写为:

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

More optimized solution: 更优化的解决方案:

#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);
}

Notes: 笔记:

  • There is no need to while loop operation 17 / 5 = 3 in integers arithmetic in C and 17 % 5 = 2 . 不需要在C中使用整数算法进行17/5 17 / 5 = 3 while loop操作,而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 . 使用此方法,您可以使用价值为N的硬币, amount / N硬币数量(可以为0,例如:整数除以amount = 9N = 10 9/10 = 0 ),剩余amount % N
  • The last case (for coin of 1) always left amount = 0 . 最后一种情况(硬币为1)始终剩余amount = 0

I agree with NetVipeC's answer. 我同意NetVipeC的回答。

I would add a note that is probably out of your assignment's scope, but might help you create better code in the future: 我会添加一条注释,该注释可能不在您的作业范围内,但可能会帮助您将来创建更好的代码:

Your code suffers from code duplication . 您的代码遭受代码重复的困扰。 To eliminate that, I would create a function and call that function several times with different arguments. 为了消除这种情况,我将创建一个函数并使用不同的参数多次调用该函数。 This process is called code reuse . 此过程称为代码重用 code reuse is neccesary for writing more complicated programs. 代码重用对于编写更复杂的程序是必要的。 Code: 码:

// a user-defined function that counts the number of coins with a specific value used 
int count_number_of_coins(int amount_left, int coin_value) {
    int count = 0;
    while(amount_left >= coin_value) {
        count++;
        amount_left -= coin_value;
    }
    return count;
}

int main(void) {
    float amount = 0;
    int cents = 0;
    int count = 0;
    int amount_left = 0;
    int coin_values[] = {25, 10, 5, 1}; // an array of ints that hold the values of the coins in cents.
    int i;

    amount = .30;

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

    printf("%d", cents);

    amount_left = cents;

    for(i=0; i<4; i++) {
        int current_count = count_number_of_coins(amount_left, coin_values[i]);
        amount_left -= current_count*coin_values[i];
        count += current_count;
    }

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

I know this code might look wierd now. 我知道这段代码现在看起来很奇怪。 I've used a few key features of the C language that you will probably learn soon: user-defined function , array and for loop . 我使用了C language的一些关键功能,您可能很快就会学到它们: user-defined functionarrayfor loop

Hope this helps. 希望这可以帮助。 Best of luck with your studies! 祝您学习顺利!


Edit: 编辑:

If you don't wanna use a user-defined function, you can avoid code duplication without it. 如果您不想使用用户定义的函数,则可以避免没有它的代码重复。 Basically you just pour the function's content inside the main function (and change names of variables): 基本上,您只是将函数的内容倒入主函数中(并更改变量的名称):

int main(void) {
    float amount = 0;
    int cents = 0;
    int count = 0;
    int amount_left = 0;
    int coin_values[] = {25, 10, 5, 1}; // an array of ints that hold the values of the coins in cents.
    int i;

    amount = .30;

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

    printf("%d", cents);

    amount_left = cents;

    for(i=0; i<4; i++) {
        while(amount_left >= coin_values[i]) {
            count++;
            amount_left -= coin_values[i];
        }
    }

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM