2015-12-02 219 views
0

我的家庭作業正在製作一個加密/解密程序,用戶輸入消息和一個具有相同字母數的密鑰。 該程序加密消息並顯示它,然後解密密碼並再次顯示該消息。 我有一個問題解密密碼,當我寫你好,關鍵是JHBZA它顯示HELPO而不是你好。代碼中有什麼問題?加密/解密程序C++

 #include <iostream> 
#include <string> 
#include <iomanip> 
using namespace std; 

int main() 
{ 
    char message[100], key[100], encryption[100], decryption[100]; 
    int msgvalue [100], msgvalue2 [100], keyvalue [100], keyvalue2 [100], sum[100], decryptvalue[100], decryptvalue2[100]; 
    int i=0; 

cout << "Enter the message: "; 
cin.getline(message, 100); 
while(message[i] != '\0') 
{ 

    msgvalue[i] = message[i]; 
    msgvalue2[i] = msgvalue[i] - 65; 
    i++; 
} 

i=0; 

cout << "Enter the key: "; 
cin.getline(key, 100); 
while(key[i] != '\0') 
{ 
    keyvalue[i] = key[i]; 
    keyvalue2[i] = keyvalue[i] -65; 
    i++; 
} 



cout << "The message is: " << setw(15) << message << endl; 
for(int i = 0; msgvalue[i] > 1; i++) 
{ 
sum [i] = msgvalue2[i] + keyvalue2[i]; 
sum[i] = sum[i] % 26; 
} 



cout << "The cipher is: " << setw(12); 

for(int i = 0; msgvalue[i] >= 65 && msgvalue[i] <= 90; i++) 
{ 
encryption[i] = sum[i] + 65; 

cout << encryption[i]; 
} 


cout << endl << "The message again is: " << setw(12); 

for(int i = 0; msgvalue[i] >= 65 && msgvalue[i] <= 90; i++) 
{ 
decryptvalue[i] =(sum[i] - keyvalue2[i]) % 26; 

if (decryptvalue[i] < 0) 
{ 
    decryptvalue[i] = -decryptvalue[i] ; 
} 


decryptvalue2[i] = decryptvalue[i] + 65; 

decryption[i] = decryptvalue2[i]; 

cout << decryption[i]; 

} 


    return 0; 
} 

enter image description here

+2

什麼是所有的反斜槓? – NathanOliver

+1

不知道,但我修好了對不起! – markos

+1

這聽起來像你可能需要學習如何使用調試器來遍歷代碼。使用一個好的調試器,您可以逐行執行您的程序,並查看它與您期望的偏離的位置。如果你打算做任何編程,這是一個重要的工具。進一步閱讀:** [如何調試小程序](http://ericlippert.com/2014/03/05/how-to-debug-small-programs/)** – NathanOliver

回答

0

'Z'= 25 'L'= 11

因此(25 + 11)%26 = 10

當你去解密,(10 - 25)%26 = -15

然後,您取這個絕對值,將其設置爲15.相反,解密值爲時要做的正確事情210 0是增加26.這將把-15變成11. 11 ='L'。

+0

完美運行!非常感謝 – markos