2015-08-22 29 views
1
#include <stdio.h> 

int main() 
{ 
    char text[1000], alpha; 
    int n; 

    printf("Please type in text:\n"); 
    scanf("%[^\n]s", text); 

    printf("\nRotation number: "); // rotates letters to the right. 
    scanf("%d",&n); 
    printf("\n"); 

    n = n % 26; // to wrap around alphabet. 

    int i = 0; 
    while (text[i] != '\0') 
    { 
     if((text[i] >= 'a' && text[i] <= 'z')) 
     { 
      alpha = text[i]; 

      text[i] += n; 

这后者字母是我不明白为什么它不工作的一部分:它的工作原理,直到凯撒密码在C:似乎无法环绕字母

  if(text[i] > 'z') 

      { 
       text[i] = 'a' + (n - (26 % (alpha - 'a'))); 
      } 

字母'd'。 'f'只给出'\ 200'。

任何想法为什么我的代码不起作用?

 } 
     i++; 
    } 

     printf("Encrypted text:\n%s", text); 

    return 0; 
} 
+0

为什么你会做这种方式?你为什么不使用'islower()'?如此多的问题...... – EOF

+0

我仍然学习用C语言编写代码,因此我宁愿自己编写所有代码,而不使用现有函数。 –

+0

我不明白它能正常工作。那么问题是什么。 – ameyCU

回答

0

我想你想要的是

text[i] = (text[i] - 'a' + n) % 26 + 'a'; 

它做到这一点

text[i] - 'a' // converts text[i] to a number between 0 and 25 
+ n   // add the cipher value 
% 26   // wrap as necessary so the value is between 0 and 25 
+ 'a'   // convert back to a letter between 'a' and 'z' 

所以循环应该是这样的

for (int i = 0; text[i] != '\0'; i++) 
{ 
    if (text[i] >= 'a' && text[i] <= 'z') 
     text[i] = (text[i] - 'a' + n) % 26 + 'a'; 
} 
+0

感谢您的答复,但是,当我用你的代码,我得到这个: 请输入文字: XYZ 转数:2 加密文本: ZCD 它应该是朱 –

+0

@HeshamSaleh我已经更新了答案。 – user3386109

+0

完美。谢谢您的帮助。你能解释一下为什么你以前的答案没有奏效吗?再次感谢。 –

1

你没有这部分理解为什么不工作:

if(text[i] > 'z') 
{ 
    text[i] = 'a' + (n - (26 % (alpha - 'a'))); 
} 

将与

if(text[i] > 'z') 
{ 
    text[i] -= 26; 
} 

UPDATE你与char工作whick可能是签名,这样加上密码,也就是说,20 z会产生一个数字,> 128简单地加以解决,即否定的。

我认为这项修正案

int alpha; // changed from char 

//... 

alpha = text[i] + n; 
if (alpha > 'z') 
    alpha -= 26; 
text[i] = alpha; 
+0

男人,我只是想发布这样的东西,并提醒'n'可能会比26大。 – EOF

+0

@EOF,我正准备添加骑乘者,这可能导致我的答案过于复杂。 –

+0

我刚刚在原始问题中看到了'n%= 26',所以它都很好。 – EOF