簡體   English   中英

為什么我對凱撒密碼的解密功能會產生錯誤的輸出?

[英]Why does my decryption function for the Caesar cipher produce faulty outputs?

我目前正在為Caesar密碼開發解密功能。 我已根據我編寫的加密功能對此模型進行了建模,與解密功能不同,該功能可以完美運行。

我的代碼編譯沒有任何錯誤並執行。 它可以用少於或少於五個字母的單詞解密,但不能用五個以上的字母以及包含兩個或更多單詞的句子解密。

當鍵的值小於等於12時,也會產生錯誤的文本輸出。 為什么會發生這些錯誤? 任何形式的幫助將不勝感激。 先感謝您。

#include <stdio.h>

/
}

問題是模運算符並不總是返回正值: -1 % 26給出-1 ,這使您的decrypt_ltr函數返回的字符不在'a' - 'z'范圍(或'A' - 'Z'范圍)。 例如,當使用密鑰2解密' a '時,您將獲得: 'a' - 'a' - key -key '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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM