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

C语言Caesar密码程序输出异常求助(CS50作业)

问题分析与修复方案

核心问题

你的凯撒密码程序输出数字而非预期字母,以及逻辑失效的原因主要有以下几点:

  • 打印格式错误:使用%i格式符会输出字符的ASCII数值,而非字符本身,应该替换为%c。
  • 大写字母偏移计算错误:偏移后应该加'A'而非'Z',否则会超出大写字母的范围。
  • 字符判断逻辑失效:变量c仅在函数开头初始化一次,循环中未更新为当前遍历的字符,导致所有判断都基于第一个字符。
  • 依赖全局变量:函数中使用全局的plaintext而非传入的str参数,不符合模块化设计原则。

修复后的完整代码

#include <cs50.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

void caesar_cipher(char str[], int shift_value);

int main(int argc, string argv[])
{
    if (argc == 2 && isdigit(*argv[1]))
    {
        int key_value = atoi(argv[1]);
        string plaintext = get_string("Plaintext: ");

        printf("Ciphertext: ");
        caesar_cipher(plaintext, key_value);
        printf("\n");
        return 0;
    }
    else
    {
        printf("Usage: ./caesar 'key'\n");
        return 1;
    }
}

void caesar_cipher(char str[], int shift_value)
{
    int n = strlen(str);
    for (int i = 0; i < n; i++)
    {
        char c = str[i];
        if (isupper(c))
        {
            printf("%c", (((c - 'A') + shift_value) % 26) + 'A');
        }
        else if (islower(c))
        {
            printf("%c", (((c - 'a') + shift_value) % 26) + 'a');
        }
        else
        {
            printf("%c", c);
        }
    }
}

关键修复点说明

  1. 修正打印格式:将所有printf("%i", ...)替换为printf("%c", ...),确保输出字符而非ASCII数值。
  2. 修正大写字母计算:把+ 'Z'改为+ 'A',保证偏移后的字符落在大写字母(A-Z)的范围内。
  3. 更新循环内的字符变量:在每次循环迭代中重新赋值c = str[i],让判断逻辑对应当前处理的字符。
  4. 移除不必要的全局变量:将plaintext、key_value改为局部变量,函数内使用传入的str参数计算长度,增强代码独立性。
  5. 简化冗余逻辑:去掉多余的if (c != '\0')判断,因为strlen已经确保循环覆盖所有有效字符。

测试验证

运行./caesar 2并输入Hello,会输出预期的Ciphertext: JGOOQ。

内容的提问来源于stack exchange,提问作者JohnHann-123

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 17:25:30