Kodewick
开始学 →
小挑战←→0 / 70

喝药水

#067小挑战结构体指针约 6 分钟

勇者有 50 点生命、2 瓶药水。drink(h) 喝一瓶:药水少 1 瓶,生命加 30,但最多 100。没有药水时什么都不做(已经写好)。main 喝了三次。

应该显示
HP: 100, potions: 0
main.c
#include <stdio.h>

struct Hero {
    int hp;
    int potions;
};

void drink(struct Hero *h) {
    if (h->potions == 0) {
        return;
    }
    // 在这里写:药水减 1,hp 加 30,超过 100 就改成 100
}

int main(void) {
    struct Hero hero = {50, 2};
    drink(&hero);
    drink(&hero);
    drink(&hero);
    printf("HP: %d, potions: %d\n", hero.hp, hero.potions);
    return 0;
}
Ctrl + Enter 也能运行
结果

写好了先点「运行」试试示例,没问题再点「提交」。