【问题标题】:Negative numbers with modulo operator in 'De-Vigenere' program'De-Vigenere' 程序中带模运算符的负数
【发布时间】: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


【解决方案1】:

问题在于模运算符处理负数的方式。

对于某些字符,您得到负值,然后模运算返回负值。你想要一个 [0, 25] 范围内的值。

您可以通过在取模数之前添加 26 来修复它。

                printf("%c", (((text[i] - 97) - (key[index] - 97)) % 26) + 97);

会变成

                printf("%c", (((text[i] - 97) - (key[index] - 97) + 26) % 26) + 97);

以同样的方式更改所有四行。

【讨论】:

  • 这也取决于哪个操作数是负数。例如-10 % 3-1,但10 % -31。要记住的规则是整数除法向 0 截断(丢弃小数部分),并且 ((a / b) * b) + (a % b) 等于 a
猜你喜欢
  • 1970-01-01
  • 2015-07-23
  • 2021-03-20
  • 2011-04-22
  • 2017-01-13
相关资源
最近更新 更多