C 中的凯撒密码:似乎无法环绕字母表的后几个字母
Caesar's Cipher in C: can't seem to wrap around the latter letters of the alphabet
#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] != '[=10=]')
{
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;
}
我想你想要的是
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] != '[=12=]'; i++ )
{
if ( text[i] >= 'a' && text[i] <= 'z' )
text[i] = (text[i] - 'a' + n) % 26 + 'a';
}
这部分你不明白为什么不起作用:
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;
#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] != '[=10=]')
{
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;
}
我想你想要的是
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] != '[=12=]'; i++ )
{
if ( text[i] >= 'a' && text[i] <= 'z' )
text[i] = (text[i] - 'a' + n) % 26 + 'a';
}
这部分你不明白为什么不起作用:
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;