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;

これは、なぜ機能しないのか理解できない部分です。

            if(text[i] > 'z')

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

文字「d」まで機能します。'f' は単に '\200' を返します。

私のコードが機能しない理由についてのアイデアはありますか?

        }
        i++;
    }

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

    return 0;
}
4

2 に答える 2

1

なぜ機能しないのか理解できないこの部分:

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

で簡単に解決できます

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

作業しているUPDATEcharはおそらく署名されているため、暗号を追加すると、たとえば 20 にz128 を超える数値、つまり負の数値が生成されます。

この修正案を提案します

int alpha;   // changed from char

//...

alpha = text[i] + n;
if (alpha > 'z')
    alpha -= 26;
text[i] = alpha;
于 2015-08-22T18:16:02.817 に答える
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';
}
于 2015-08-22T17:56:39.127 に答える