1

我目前正在研究凯撒密码的解密功能。我已经根据我编写的加密函数对此进行了建模,与解密函数不同,它运行良好。

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

此外,当键的值 <=12 时,它也会产生错误的文本输出。为什么会出现这些错误?任何形式的帮助将不胜感激。先感谢您。

#include <stdio.h>

/
}
4

1 回答 1

0

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

由于您的密钥保证在 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;
}
于 2019-04-26T09:19:19.960 回答