Problem using modulo with negative numbers in decryption program

前端 未结 2 644
广开言路
广开言路 2021-01-23 01:19

I\'m rather new to C and have recently been working on making a simple encryption/decryption program. I managed to get the encryption fine, but I\'ve hit a road block with the

相关标签:
2条回答
  • 2021-01-23 01:52

    Instead of using asciinum % 26, use (asciinum + 26) % 26, this will have you using modulus on positive numbers, at the cost of an extra addition each time through the cycle.

    0 讨论(0)
  • 2021-01-23 02:03

    In pre-C99 C, the behaviour of % for negative numbers is implementation-defined. In C99 onwards, it's defined, but doesn't do what you want.

    The easiest way out is to do:

    ((asciinum + 26) % 26)
    

    Assuming asciinum can never get lower than -26.

    0 讨论(0)
提交回复
热议问题