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

C# Windows Forms凯撒密码仅可加密无法解密、位移大于5报错问题

问题根因

C# 中的取模运算符%对负数运算时会返回负余数,你当前的解密逻辑仅做了减法运算,当input[i] - key的结果小于对应字符基准值(大写字母基准为'A'、小写为'a'、数字为'0'、特殊字符为'!')时,差值取模后仍为负数,最终加上基准值后会落到正常可显示字符范围外,因此输出乱码。
对应你给出的测试场景可直接验证:密文第一个字符为大写B(ASCII值为66),密钥为20,解密时的计算流程如下:

(66 - 20) - 'A' = 46 - 65 = -19
-19 % 26 = -19(C# 负数取模规则)
-19 + 'A' = -19 + 65 = 46

46对应的字符为.,和你解密输出的第一个乱码字符完全匹配。

修复方案

对解密逻辑中所有的取模运算,先加上对应模数保证结果为正,再做一次取模即可。修改后的doDecryption方法代码如下:

private static string doDecryption(string input, int key)
{
    string output2 = string.Empty;

    for (int i = 0; i < input.Length; i++)
    {
        if (char.IsLetter(input[i]) && char.IsUpper(input[i]))
        {
            // 加26再取模,保证余数为正
            char ch = (char)((((input[i] - key) - 'A' + 26) % 26) + 'A');
            output2 += ch;
        }
        else if (char.IsLetter(input[i]) && char.IsLower(input[i]))
        {
            char ch = (char)((((input[i] - key) - 'a' + 26) % 26) + 'a');
            output2 += ch;
        }
        else if (char.IsNumber(input[i]))
        {
            char ch = (char)((((input[i] - key) - '0' + 10) % 10) + '0');
            output2 += ch;
        }
        // 注:原代码此处的else if(char.IsLetter(input[i]))分支永远不会触发,前面已经覆盖了大小写字母的判断,可直接删除
        else if (!char.IsWhiteSpace(input[i]))
        {
            char ch = (char)((((input[i] - key) - '!' + 95) % 95) + '!');
            output2 += ch;
        }
        else
            output2 += input[i];
    }
    return output2;
}

修改后使用你的测试用体验证:输入密文Byffi qilfx、密钥20,解密即可得到正确的明文Hello world。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 16:45:02