[英]Negative numbers with modulo operator in 'De-Vigenere' program
我正在制作一个解密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++;
}
输入:MyName
关键:qwerty
我该如何解决?
问题在于模运算符处理负数的方式。
对于某些字符,您将获得负值,然后模运算将返回负值。 您想要一个在[0,25]范围内的值。
您可以在取模数之前加26来修复它。
printf("%c", (((text[i] - 97) - (key[index] - 97)) % 26) + 97);
会成为
printf("%c", (((text[i] - 97) - (key[index] - 97) + 26) % 26) + 97);
以相同的方式更改所有四行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.