#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;
}
最佳答案
这部分你不明白为什么不起作用:
if(text[i] > 'z')
{
text[i] = 'a' + (n - (26 % (alpha - 'a')));
}
可以用
简单地解决if(text[i] > 'z')
{
text[i] -= 26;
}
UPDATE 你正在使用 char
which 可能已签名,因此将密码,比如 20 添加到 z
将产生一个数字> 128,即负数。
我建议修改
int alpha; // changed from char
//...
alpha = text[i] + n;
if (alpha > 'z')
alpha -= 26;
text[i] = alpha;
关于C 中的凯撒密码 : can't seem to wrap around the latter letters of the alphabet,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32159063/