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

CS50中我的凯撒密码算法实现存在错误,请求技术排查

CS50凯撒密码算法故障排查求助

我在CS50课程中实现的凯撒密码算法无法正常工作。我已经实现了密钥为正数的校验逻辑,并且严格按照题目给出的加密公式编写代码,但程序依然运行异常,请求帮忙排查问题。

算法说明

更正式地说,凯撒算法(即密码)通过将每个字母旋转k个位置来加密消息。更准确地说,若p为明文(未加密消息),p_i为p中的第i个字符,k为密钥(非负整数),则密文中的每个字母c_i为...

实现代码

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

int convertToInt(string input);

int main(int argc, string argv[])
{
    string testKey= argv[1];
    int key= convertToInt(testKey);

    if(argc>2)
    {
        printf("Usage: ./caesar key");
        return 1;
    }
    else
    {
        for(int i=0; i<strlen(testKey); i++)
        {
            if(testKey[i]<48||testKey[i]>57)
            {
                printf("Usage: ./caesar key");
                return 1;
            }
        }
        if(key<0)
        {
            printf("Usage: ./caesar key");
            return 1;
        }
    }

    string phrase= get_string("plaintext:  ");

    for(int i=0; i<strlen(phrase); i++)
    {
        if((int)phrase[i]>='a'&&(int)phrase[i]<='z')
        {
            phrase[i]=(((phrase[i]- 'a')+ key)%26) +'a';
        }
        if((int)phrase[i]>='A'&&(int)phrase[i]<='Z')
        {
            phrase[i]=(((phrase[i]- 'A')+ key)%26) +'A';
        }
    }
    printf("chiphertext: %s \n", phrase);

}

int convertToInt(string input)
{
    int convertedValue=0;
    for(int i=0; i<strlen(input); i++)
    {
        convertedValue=convertedValue* 10+ (int)input[i];
    }
    return convertedValue;
}

我已完成以下校验逻辑:

  • 校验命令行参数数量是否合法(不超过2个)
  • 校验密钥是否由纯数字字符组成
  • 校验转换后的密钥是否为非负整数

加密逻辑严格遵循题目指定的公式,但程序仍无法正常运行,希望能帮忙找出问题所在。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 14:57:36