【发布时间】:2018-11-07 17:45:49
【问题描述】:
当我尝试解密消息时,输出不是应该的。我查阅了 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)? e
输入消息(100 个字符或更少): 你好
输入键: 3
加密消息:khoor
用于解密的 GCC 输出:
您要加密 (e) 还是解密 (d)? d
输入消息(100 个字符或更少): 胡尔
输入键: 3
解密消息:nkrru
【问题讨论】:
-
解密时需要减去密钥。好像你复制粘贴错误(抱歉评论答案切换)
标签: c