谁能告诉我凯撒算法有什么问题吗?

标签 c cs50 caesar-cipher

当我使用数字 4-22 时,输出很不稳定,我不明白为什么。非常感谢您的帮助,我也想知道为什么这不起作用。

#include<cs50.h>
#include<stdio.h>
#include<string.h>
int main(void)
{
    int shifts;
    int enc;
    printf("What is your message ");
    string message = get_string();
    printf("By how many letters do you want to shift?");
    scanf("%d",&shifts);

    for(int i=0;i<strlen(message);i++)
    {
           enc=((message[i] - 89)+shifts)%26;
           printf("%c",enc + 89);
    }
    printf("\n");
}

最佳答案

在 for 循环中,您应该检查字符是大写、小写还是两者都不是。数字89也是错误的,那就是“Y”,你可能想要的是65或97,分别是“a”和“A”。 for 循环应更改为:

#include <ctype.h> // For isupper()/islower()
for(int i = 0; i < strlen(message); i++)
{
    if(isupper(message[i])) { // Check if current char is uppercase
        enc=((message[i] - 'A')+shifts)%26; // Apply cipher
        printf("%c",enc + 'A'); 
    } else if(islower(message[i])) { // Check if current char is lowercase
        enc=((message[i] - 'a')+shifts)%26; // Apply cipher
        printf("%c",enc + 'a');
    } else { // Print char without change
        printf("%c", message[i]);
    }
}

请注意使用“A”和“a”而不是 65 和 97,这些将在编译时转换为相应的整数文字。还有其他方法可以编写此代码,这可能甚至不是最干净的方法(例如多个 printf()),但它应该说明这是如何工作的以及应该完成的。

关于谁能告诉我凯撒算法有什么问题吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44877733/

相关文章:

c - 在传递的一维数组 C 中使用 if 语句,函数 array(int *) 中类型 'int(int *)' 的大小未知或为零

c - 指针和多维数组

c - 根据输入执行一段代码

CS50 PSet 2 : Vigenere cipher Segmentation Fault

python - 凯撒移位密码

ruby - 在此凯撒密码中, "print i[-1]"是如何从 z 换行到 a 的?

c - 为什么这段代码要调用 rand() 两次才能获得至少 N 个随机位?

cs50 pset3 - 排序

c++ - 凯撒密码删除数据

c - 汇编中的堆栈与 c 中的堆栈?