2015-08-22 45 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