我目前正致力于Caesar密码的解密功能。我已经根据我编写的加密函数对此进行了建模,与解密函数不同,它的工作方式非常完美。
我的代码编译没有任何错误并执行。它可以用五个字母或更少的字母进行解密,但是不能用超过五个字母以及包含两个或更多单词的句子进行解密。
当键的值<= 12时,它还会为文本生成错误输出。为什么会出现这些错误?任何形式的帮助将不胜感激。先感谢您。
#include <stdio.h>
/
}
问题是模运算符并不总是返回正值:-1 % 26
给出-1
,这使得你的decrypt_ltr
函数返回'a'
-'z'
范围之外的字符(或'A'
-'Z'
范围)。例如,当使用2的密钥解密'a
'时,您将获得:'a' - 'a' - key
= -key
。然后你会做-key + 'a'
,它仍然低于'a'
。
由于您的密钥保证在1到26之间,因此您只需在(alpha-'A') - key
值中添加26,如下所示:
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;
}