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

CS50 Caesar密码作业IDE运行正常但check50报错求助

错误点排查

  • 多余输出了明文行:check50的测试用例只要求输出ciphertext: 加密结果这一行,你代码里多写了printf("plaintext: %s\n",plaintext);,这是第一个报错的直接原因,直接删掉这行即可。
  • 返回值逻辑错误:
    • 只有程序异常退出(参数个数不对、参数不是纯数字)的时候才需要返回1
    • 程序正常执行完成要返回0,你最开始不管什么情况最后都return 1,修改后又全改成return 0,导致参数错误的场景返回值不符合要求。
  • 密文字符串没有加结束符:你定义的cyphertext是字符数组,循环赋值完成后没有手动加'\0',输出的时候可能会出现多余乱码。
  • 冗余的index数组:plaintext[i] - 'A'本身就是0-25的数字,不需要再通过index数组取值,这部分代码可以直接简化。

修正后代码

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

int main(int argc, char* argv[])
{
    string plaintext;
    int n;
    char cyphertext[100];
    int key;

    if (argc != 2)
    {
        printf("Usage: ./caesar key\n");
        return 1;
    }

    string str = argv[1];
    for(int i = 0;i < strlen(str); i++)
    {
        if(!isdigit(str[i]))
        {
            printf("Usage: ./caesar key\n");
            return 1;
        }
    }

    key = atoi(str);
    plaintext = get_string("Text: ");
    int len = strlen(plaintext);
    for(int i = 0; i < len; i++)
    {
        if(isupper(plaintext[i]))
        {
            n = plaintext[i] - 'A';
            cyphertext[i] = ((n + key) % 26) + 'A' ;
        }
        else if(islower(plaintext[i]))
        {
            n = plaintext[i] - 'a';
            cyphertext[i] = ((n + key) % 26 ) + 'a';
        }
        else
        {
            cyphertext[i] = plaintext[i];
        }
    }
    cyphertext[len] = '\0';
    printf("ciphertext: %s\n",cyphertext);

    return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 15:27:02