当我尝试解密一条消息时,输出不是它应该的样子。我查阅了 Caesar Cipher 并理解了这个概念,但从我所看到的来看,一切似乎都是正确的。会不会是我在使用 switch 语句?
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main(void){
char phrase[100], option, ph;
int key;
printf("Would you like to encrypt (e) or decrypt (d)? \n");
scanf(" %c", &option);
printf("Enter a message (100 characters or less): \n");
scanf(" %s", phrase);
printf("Enter key: \n");
scanf(" %i", &key);
switch(option){
case 'e':
{
for(int i = 0; phrase[i] != '\0'; i++){
ph = phrase[i];
if(ph >= 'a' && ph <= 'z'){
ph = ph + key;
if(ph > 'z'){
ph = ph - 'z' + 'a' - 1;
} //end of if
phrase[i] = ph;
} // end of if
else if(ph >= 'A' && ph <= 'Z'){
ph = ph + key;
if(ph > 'Z'){
ph = ph - 'Z' + 'A' - 1;
}
phrase[i] = ph;
} // end of else if
} // end of for
printf("Encrypted message: %s\n", phrase);
break;
} // end of case 'e'
case 'd':
{
for(int i = 0; phrase[i] != '\0'; i++){
//~ phrase[i] = phrase[i] + 3;
ph = phrase[i];
if(ph >= 'a' && ph <= 'z'){
ph = ph + key;
if(ph > 'z'){
ph = ph - 'z' + 'a' + 1;
}
phrase[i] = ph;
} // end of if
else if(ph >= 'A' && ph <= 'Z'){
ph = ph + key;
if(ph > 'Z'){
ph = ph - 'Z' + 'A' + 1;
} // end of if
phrase[i] = ph;
} // end of else if
} // end of for
printf("Decrypted message: %s\n", phrase);
break;
} // end of case 'd'
} // end of switch
} // end of function
用于加密的 GCC 输出:
您想加密 (e) 还是解密 (d)? 电子
输入消息(100 个字符或更少): 你好
输入键: 3
加密信息:khoor
用于解密的 GCC 输出:
您想加密 (e) 还是解密 (d)?
输入消息(100 个字符或更少): 呼尔
输入键: 3
解密信息:nkrru
最佳答案
您的加密逻辑和解密逻辑是相同的,即对于解密,您在应该减去的时候添加了 key 。您还需要更改低于 'a'
的溢出检查:
case 'd':
{
for(int i = 0; phrase[i] != '\0'; i++){
//~ phrase[i] = phrase[i] + 3;
ph = phrase[i];
if(ph >= 'a' && ph <= 'z'){
ph = ph - key; // subtract
if(ph < 'a'){ // switch wraparound check
ph = ph + 'z' - 'a' - 1;
}
phrase[i] = ph;
} // end of if
else if(ph >= 'A' && ph <= 'Z'){
ph = ph - key; // subtract
if(ph < 'a'){ // switch wraparound check
ph = ph + 'Z' - 'A' - 1;
} // end of if
phrase[i] = ph;
} // end of else if
} // end of for
printf("Decrypted message: %s\n", phrase);
break;
} // end of case 'd'
关于凯撒密码不解密,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53194948/