2017-07-03 101 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()),但它应该说明这是如何工作和应该完成的。

相关问题