You need to enable JavaScript to run this app. 为何Move提示重复打印?C语言小游戏代码问题求助
优惠活动
大模型
产品
解决方案
定价
更多

为何Move提示重复打印?C语言小游戏代码问题求助

问题解决方案

1. 解决"Move: "重复打印的问题

问题根源是scanf("%c%d", &move, &attack)的读取逻辑:之前用scanf输入数值或字符串后,输入缓冲区会残留换行符,后续%c会直接读取这个换行符作为有效输入,导致循环里的printf("Move: ")被重复触发。

修复方法是在%c前添加一个空格,让scanf自动跳过所有空白字符(包括换行、空格等):

scanf(" %c%d", &move, &attack);

2. 避免生命值为0时打印当前生命值

当前代码是先扣除生命值就打印状态,再判断是否触发死亡逻辑。需要调整顺序:先计算新生命值,仅当生命值仍大于0时才打印状态,否则直接退出循环。

修改后的攻击分支代码:

if(move=='A'){
    hero1.health = hero1.health - (attack-hero1.defense);
    // 只在生命值大于0时打印当前状态
    if(hero1.health > 0){
        printf("\n%s current health - %d\n", hero1.coolName, hero1.health);
    } else {
        // 生命值为0,直接退出循环,不打印状态
        break;
    }
}

完整修改后的代码

typedef struct{
    char coolName[100];
    int health;
    int defense;
}Hero;

int main(){
    Hero hero1;
    
    printf("Enter hero name: ");
    scanf("%s", hero1.coolName); // 数组名本身就是地址,无需加&
    printf("Enter health: ");
    scanf("%d", &hero1.health);
    printf("Enter defense: ");
    scanf("%d", &hero1.defense);
    char move;
    int attack;
       
    do{ 
        printf("Move: ");
        scanf(" %c%d", &move, &attack); // 修复换行符读取问题
        if(move=='A'){
            hero1.health = hero1.health - (attack-hero1.defense);
            // 仅在生命值>0时打印当前状态
            if(hero1.health > 0){
                printf("\n%s current health - %d\n", hero1.coolName, hero1.health);
            } else {
                break;
            }
        }else if(move=='S'){
            printf("I surrender\n");
            break;
        }
    }while(hero1.health>0);
    printf("%s has fallen\n", hero1.coolName);

    return 0;
}

内容的提问来源于stack exchange,提问作者tiredcomscistudent

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 10:15:28