[英]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.