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

数字转中文拼音C程序异常:测试正常但检测平台判定错误

问题排查与修复

核心问题

你的代码存在两个关键问题,其中第一个是导致检测网站判定错误的直接原因:

  1. 未处理fgets读取的换行符:fgets会将用户输入末尾的换行符\n一并读入字符串。当处理到这个换行符时,ipt[i] - '0'会得到一个非0-9的数值,导致越界访问py数组,触发未定义行为(可能输出乱码、程序崩溃,或者不符合检测网站的输出规范)。
  2. 循环内重复调用strlen:每次循环都计算字符串长度,虽然不影响功能,但会降低代码效率。

修复后的代码

#include <stdio.h>
#include <string.h>

int main() {
    char ipt[100];
    char py[10][6] = {"ling", "yi", "er", "san", "si", "wu", "liu", "qi", "ba", "jiu"};

    fgets(ipt, 100, stdin);
    
    // 去掉末尾的换行符(如果存在)
    size_t len = strlen(ipt);
    if (len > 0 && ipt[len - 1] == '\n') {
        ipt[len - 1] = '\0';
        len--;
    }

    int i = 0;
    if (ipt[0] == '-') {
        printf("%s ", "fu");
        i++;
    }

    for (; i < len; i++) {
        if (i < len - 1)
            printf("%s ", py[ipt[i] - '0']);
        else
            printf("%s", py[ipt[i] - '0']);
    }
    return 0;
}

修复说明

  • 处理换行符:通过strlen获取长度后,检查最后一个字符是否为\n,若是则替换为字符串结束符\0,确保后续只处理有效数字字符。
  • 提前计算长度:将字符串长度提前计算并存储,避免循环内重复调用strlen,提升代码效率。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 05:45:09