2017-07-03 99 views
0

當我使用數字4-22時,輸出不可靠,我不知道爲什麼。幫助將不勝感激,我也想知道爲什麼這不起作用。誰能告訴我我的凱撒算法有什麼問題?

#include<cs50.h> 
#include<stdio.h> 
#include<string.h> 
int main(void) 
{ 
    int shifts; 
    int enc; 
    printf("What is your message "); 
    string message = get_string(); 
    printf("By how many letters do you want to shift?"); 
    scanf("%d",&shifts); 

    for(int i=0;i<strlen(message);i++) 
    { 
      enc=((message[i] - 89)+shifts)%26; 
      printf("%c",enc + 89); 
    } 
    printf("\n"); 
} 
+2

數字'89'似乎是錯誤的。另外,您應該分開處理小寫和大寫。 – nglee

+2

使用字符常量,而不是像'89'這樣的幻數, –

+0

另外,代碼中有內存泄漏。 –

回答

0

在for循環中,你應該檢查字符是大寫還是小寫,或者都不是。 89號也是錯誤的,那就是'Y',你可能想要的分別是65或97,'a'和'A'。 for循環應改爲類似:

#include <ctype.h> // For isupper()/islower() 
for(int i = 0; i < strlen(message); i++) 
{ 
    if(isupper(message[i])) { // Check if current char is uppercase 
     enc=((message[i] - 'A')+shifts)%26; // Apply cipher 
     printf("%c",enc + 'A'); 
    } else if(islower(message[i])) { // Check if current char is lowercase 
     enc=((message[i] - 'a')+shifts)%26; // Apply cipher 
     printf("%c",enc + 'a'); 
    } else { // Print char without change 
     printf("%c", message[i]); 
    } 
} 

的使用注意事項「A」和「A」,而不是65和97,這將轉化爲在編譯時對應的整數常量。還有其他的方法來寫這個,這可能不是最乾淨的方法(例如多個printf()),但它應該說明這是如何工作和應該完成的。

相關問題