gpt4 book ai didi

c - 为什么我的凯撒密码解密函数会产生错误的输出?

转载 作者:太空宇宙 更新时间:2023-11-04 04:12:14 24 4
gpt4 key购买 nike

我目前正在研究凯撒密码的解密函数。我根据我编写的加密函数对其进行了建模,与解密函数不同,它工作得很好。

我的代码编译没有任何错误并执行。它能够解密五个字母或更少的单词,但不能解密超过五个字母以及包含两个或更多单词的句子。

当键的值 <=12 时,它还会为文本生成错误输出。为什么会出现这些错误?任何形式的帮助将不胜感激。提前谢谢你。

#include <stdio.h>

/
}

最佳答案

问题是模运算符并不总是返回正值:-1 % 26 给出 -1,这使得您的 decrypt_ltr 函数返回 'a' 之外的字符 - 'z' 范围(或 'A'-'Z' 范围)。例如,当用 key 2解密'a'时,你将得到:'a' - 'a' - key = -key。然后你将执行 -key + 'a',这仍然小于 'a'

由于您的 key 保证在 1 到 26 之间,您可以简单地将 26 添加到 (alpha-'A') - key 值,如下所示:

char decrypt_ltr(char alpha, int key) 
{
if (alpha >= 'A' && alpha <= 'Z')
{
alpha = ((alpha-'A') - key + 26) % 26 + 'A'; // the 26 ensures that the value
// is positive before the modulo
// operator is applied and is
// removed by the modulo operator
}
else if(alpha >= 'a' && alpha <= 'z')
{
alpha = ((alpha-'a') - key + 26) % 26 + 'a';
}

return alpha;
}

关于c - 为什么我的凯撒密码解密函数会产生错误的输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55859798/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com