Expression Result Unused Greedy Algorithm

后端 未结 3 1942
南方客
南方客 2021-01-28 08:18

I have run this program and get the error expression result unused. I may be doing something simple wrong, but I have spent the day trying to figure it out to no avail. Any help

3条回答
  •  囚心锁ツ
    2021-01-28 08:32

    I would remain to be convinced about your loop structure. There's the division operator that can be used to good effect:

    int total = 0;
    int ncoins;
    int amount = GetFloat() * 100;
    
    assert(amount >= 0);
    
    ncoins = amount / 25;
    total += ncoins;
    amount -= ncoins * 25;
    
    assert(amount < 25);
    ncoins = amount / 10;
    total += ncoins;
    amount -= ncoins * 10;
    
    assert(amount < 10);
    ncoins = amount / 5;
    total += ncoins;
    amount -= ncoins * 5;
    
    assert(amount < 5);
    total += amount;
    

    That's written out longhand; you could devise a loop, too:

    int values[] = { 25, 10, 5, 1 };
    enum { N_VALUES = sizeof(values) / sizeof(values[0]) };
    
    int total = 0;
    int ncoins;
    int amount = GetFloat() * 100;
    
    assert(amount >= 0);
    
    for (int i = 0; i < N_VALUES && amount > 0; i++)
    {
        ncoins = amount / values[i];
        total += ncoins;
        amount -= ncoins * values[i];
    }
    
    assert(amount == 0);
    

提交回复
热议问题