【发布时间】:2016-06-16 07:33:48
【问题描述】:
我正在制作一个解密 vigenere 密码的程序。用户只能给出字母键。
for (int i = 0, counter = strlen(text); i < counter; i++)
{
// prints non-alphabetical characters straight away
if (!isalpha(text[i]))
{
printf("%c", text[i]);
}
else
{
// for index of key
index = meta % strlen(key);
if (islower(text[i]))
{
// separate cases depending upon case of key
if (islower(key[index]))
{
printf("%c", (((text[i] - 97) - (key[index] - 97)) % 26) + 97);
}
else
{
printf("%c", (((text[i] - 97) - (key[index] - 65)) % 26) + 97);
}
}
else
{
if (islower(key[index]))
{
printf("%d", (((text[i] - 65) - (key[index] - 97)) % 26) + 65);
}
else
{
printf("%c", (((text[i] - 65) - (key[index] - 65)) % 26) + 65);
}
}
// incrementing for next key alphabet
meta++;
}
维吉尼:
输入:我的名字
密钥:qwerty
- 输出:CuRrfc
德维吉纳:
- 输入:CuRrfc
- key:qwerty
- 预期输出:我的姓名
- 给定输出:3_NaSK
我该如何解决?
【问题讨论】:
-
如果您知道operator precedence 有问题,您可能知道问题出在哪里,所有运算符优先级问题的解决方案都是使用括号。
-
另外,请尽量避免使用magic numbers。如果通过例如
65你的意思是ASCII 编码为'A'然后使用'A'。 -
此外,我假设
meta在您的两个程序中都已正确初始化? -
是的。元标记已初始化。我一开始就错了。问题不在于运算符优先级。它与模运算符和负数一起使用。
标签: c encryption vigenere