You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言简易石头剪刀布程序输出异常问题求助

C语言石头剪刀布程序异常问题排查

问题描述

凭借有限的C语言知识编写了一款简易石头剪刀布程序,但运行时出现异常:需输入两个数字(1代表剪刀、2代表布、3代表石头)后,程序才会打印提示信息,且最终的胜负或平局结果语句无法输出。程序输出顺序与预期不符,期望达到类似C++中cout与if语句的执行效果,仅需排查现有代码的问题,无需专业的实现方案。

程序输出示例

1
3
Press 1 for scissors, 2 for paper or 3 for rock.

Same for player two.

现有代码

#include <stdio.h>

int main() {
    printf("Press 1 for scissors, 2 for paper or 3 for rock. \n");
    int f;
    int h;
    scanf("%d", &f);
    printf("\nSame for player two.");
    scanf("%d", &h);
    if (f == h) {
        printf("Tie\n");
    }
    
    if (f == 1 && h == 2) {
        printf("Player 1 won\n");
    }
    
    if (f == 2 && h == 1) {
        printf("Player 2 won\n");
    }

    if (f == 2 && h == 3) {
        printf("Player 1 won\n");
    }
    
    if (f == 3 && h == 2) {
        printf("Player 2 won\n");
    }
    
    if (f == 3 && h == 1) {
        printf("Player 1 won\n");
    }
    
    if (f == 1 && h == 3) {
        printf("Player 2 won\n");
    }
    
    return 0;   
}

问题排查与修复

1. 输出缓冲导致提示延迟显示

C语言的printf输出默认采用行缓冲模式,只有当输出内容包含换行符\n,或者缓冲区被手动刷新时,内容才会立刻显示到屏幕上。

  • 现有代码中第二个提示printf("\nSame for player two.")没有结尾的换行符,导致这条提示被留在缓冲区中,直到后续操作触发缓冲刷新,所以会出现输入完两个数字后才一起显示提示的情况。
  • 修复:将该语句修改为printf("\nSame for player two.\n");,通过换行符强制刷新缓冲区,让提示及时显示。

2. 结果输出的缓冲问题

虽然结果语句都带有\n,但如果前面的缓冲问题没解决,可能导致结果也被延迟显示。修复上述换行问题后,结果会在输入第二个数字后立刻输出。

修改后的核心代码片段:

printf("Press 1 for scissors, 2 for paper or 3 for rock. \n");
int f;
int h;
scanf("%d", &f);
printf("\nSame for player two.\n");  // 添加结尾换行
scanf("%d", &h);
// 后续判断逻辑不变

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 18:43:29