【问题标题】:Caesar Cipher Negative Numbers Issue凯撒密码负数问题
【发布时间】:2019-02-01 05:37:00
【问题描述】:

我正在尝试编写一个凯撒密码程序,该程序接受一个参数,将其转换为一个整数,并使用它来将字母沿某个方向移动(正数将其向前移动,负数将其向后移动。所以到目前为止,所有程序都适用于所有正数,但不适用于负数。

#include <stdio.h>
#include <stdlib.h>
#include <math.h>


int encrypt(int character, int shift);

int main(int argc, char * argv[]) {

    int shift = atoi(argv[1]);
    if (shift >= 26) {
        shift = ((shift + 26) % 26);
    }

    int character = getchar();

    while (character != EOF) {
        int new_character = encrypt(character, shift);
        putchar(new_character);
        character = getchar();
    }

    return 0;

}

int encrypt(int character, int shift) {
    int ch = character;
    int negShift = shift;

    if (ch >= 'a' && ch <= 'z') {
        ch = ch + shift;
        if (ch > 'z') {
            ch = ch - 'z' + 'a' - 1;
        }
    } else if (ch >= 'A' && ch <= 'Z') {
        ch = ch + shift;
        if (ch > 'Z') {
            ch = ch - 'Z' + 'A' - 1;
        }
    }

    return ch;
}

【问题讨论】:

  • 当shift为负数时,需要检查if (ch &lt; 'a') ...

标签: c negative-number caesar-cipher


【解决方案1】:

当ch &lt; 'a' or ch &lt;'A' 时,您可以将add 26 转换为ch。 考虑下面的例子。

    if(ch < 'a')
     {
      ch  = ch + 26;
     } 

完整代码。

int encrypt(int character, int shift) {
    int ch = character;
    int negShift = shift;

    if (ch >= 'a' && ch <= 'z') {
        ch = ch + shift;
        if (ch > 'z') {
            ch = ch - 'z' + 'a' - 1;
        }

         else if(ch < 'a')
         {
            ch  = ch + 26; //Here
         } 

    } else if (ch >= 'A' && ch <= 'Z') {
        ch = ch + shift;
        if (ch > 'Z') {
            ch = ch - 'Z' + 'A' - 1;
        }

        else if(ch < 'A')
        {
            ch = ch + 26; // Here 
        }

    }

    return ch;
}

【讨论】:

    猜你喜欢
    • 2019-12-09
    • 1970-01-01
    • 1970-01-01
    • 2019-04-26
    • 2014-03-07
    • 2020-05-31
    • 2014-02-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多