c - 如果用户选择特定功能,则结束循环

标签 c function loops pointers do-while

嗨,我需要一点帮助来解决问题!

我有一个包含循环的主类。 在这个循环中,用户可以调用不同的函数来做不同的事情,但我希望如果用户选择某个函数,它会显示一条消息,然后循环结束。

这是我的代码:

#include <stdio.h>

void rest_at_inn();
void train();
void battle_demon_lord();
void Quit_Game();

int main() {

    //Declare variable and pointer
    float days_remaining = 8;
    int current_hp = 10;
    int hp_remaining = 10;
    int MAX = 10;
    int experience = 0;
    int selection;

    //Loops a menu that asks the user to make a selectio and repet it until either days or HP are less or equal to zero
    do {
        printf("Days remaining: %f, HP: %d, EXP: %d\n\n", days_remaining, hp_remaining, experience);
        printf("1 - Rest at Inn\n");
        printf("2 - Train\n");
        printf("3 - Fight the Demon Lord\n");
        printf("4 - Quit Game\n\n");
        printf("Select: \n");
        scanf("%d", &selection);
        printf("\n");

        //Execute the selection
        switch (selection) {
            case 1:
                rest_at_inn(&days_remaining, &hp_remaining, &MAX);
                break;
            case 2:
                train(&days_remaining, &hp_remaining, &experience);
                break;
            case 3:
                battle_demon_lord(&current_hp);
                break;
            case 4:
                Quit_Game();
                break;
        }

    } while (days_remaining > 0 && current_hp > 0);

    return 0;

}

//This function reduces the days by 1 and resets the HP to 10

void rest_at_inn(float *days_remaining, int *hp_remaining, int *MAX) {

    *hp_remaining = 10;
    *days_remaining -= 1;
    if (*days_remaining > 0)
        printf("You rested up the at the inn\n\n");
    else /*(*days_remaining<=0)*/
        printf("Game Over");

}

//This function reduces the days by 0.5 and the HP by 2 and adds 10 to the experience

void train(float *days_remaining, int *hp_remaining, int *experience) {

    *experience += 10;
    *hp_remaining = *hp_remaining - 2;
    *days_remaining = *days_remaining - 0.5;
    printf("You did some training!\n\n");

}

//This function sets the HP to 0 and prints a string

void battle_demon_lord(int *current_hp) {

    *current_hp = 0;
    printf("He's too strong!\n\n");
    printf("Game Over!");
}

// This function prints a string

void Quit_Game() {

    printf("Good bye!\n\n");

}

我认为它应该是 do_while 中的一个参数,但对我没有任何作用。

最佳答案

您需要为用户选择 4 时添加退出条件。

你可以这样做:

} while (days_remaining>0 && current_hp>0 && selection != 4);

或者这个:

case 4 :
    Quit_Game();
    return 0;

或者这个:

void Quit_Game()  {

    printf ("Good bye!\n\n");
    exit(0);

}

关于c - 如果用户选择特定功能,则结束循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33174753/

相关文章:

c - 没有第二个条件的循环,即 bool 检查?

c - 优化一个简单的 pinball 求解器

objective-c - Objective-C 中什么时候我的 const 应该是静态的?

C - 调用函数时参数错误

python - 不了解python的内部功能

c - 为什么输出是 36 而不是 24?

C:如何shmat一个结构?

c - printf的返回类型是什么

java - 尝试将 Dart 程序转换为 Java

R,for 循环,可扩展的解决方案