编辑代码

#include <stdio.h>
#include <stdlib.h>

typedef struct {
    const char *name;
    int weight;
    int value;
    float costPerformance;
} Fruit;

int compare(const void *f1, const void *f2) {
    return ((Fruit *)f2)->costPerformance - ((Fruit *)f1)->costPerformance;
}

void fillBackpack(Fruit fruits[], int numFruits, int capacity) {
    float totalValue = 0.0;
    int i, currentWeight;
    printf("装背包策略:\n");
    for (i = 0; i < numFruits && capacity > 0; i++) {
        if (fruits[i].weight <= capacity) {
            currentWeight = fruits[i].weight;
            capacity -= currentWeight;
        } else {
            currentWeight = capacity;
            capacity = 0;
        }
        totalValue += fruits[i].costPerformance * currentWeight;
        printf("拿走 %d 公斤 (%.2f%%) 的 %s\n", currentWeight, ((float)currentWeight / fruits[i].weight) * 100, fruits[i].name);
    }
    printf("总价值: %.2f\n", totalValue);
}

int main() {
    Fruit fruits[] = {
        {"苹果", 15, 300},
        {"香蕉", 18, 180},
        {"橘子", 10, 150},
        {"猕猴桃", 9, 270}
    };
    int numFruits = sizeof(fruits) / sizeof(fruits[0]);
    int backpackCapacity = 20;

    // 计算每种水果的性价比
    for (int i = 0; i < numFruits; ++i) {
        fruits[i].costPerformance = (float)fruits[i].value / fruits[i].weight;
    }

    // 按照性价比降序排序水果
    qsort(fruits, numFruits, sizeof(Fruit), compare);

    // 现在,装背包
    fillBackpack(fruits, numFruits, backpackCapacity);

    return 0;
}