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

C语言实现Caesar cipher输出错误:偏移按ASCII而非指定字母表计算

问题定位与修复方案

错误原因

  • 误用输入字符串的遍历下标i作为字母表的查询索引:代码中alphabet[i]的i是当前处理字符在输入串中的位置,和当前字符本身在字母表中对应的位置完全无关,计算逻辑从根本上错误。
  • 偏移后未做26字母的范围约束:没有对偏移结果做模26的归一化处理,负偏移会导致计算出的ASCII值落在小写字母范围外,最终输出[、\这类符号。

修复后的核心代码

void    cesar(char *str, int shift)
{
    int     i = 0;
    int     pos, new_pos;
    while (str[i] != '\0')
    {
        if (str[i] >= 'a' && str[i] <= 'z')
        {
            // 计算当前字符在字母表中的索引 0~25
            pos = str[i] - 'a';
            // 计算偏移后的索引,加26再模26处理负偏移的情况
            new_pos = (pos + shift % 26 + 26) % 26;
            // 替换为偏移后的字符
            str[i] = 'a' + new_pos;
        }
        i++;
    }
    printf("%s\n", str);
}

验证结果

使用你的测试用例调用cesar(temp, -6),输出结果为预期的ceci est la seconde page du livre。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 03:06:02