简单凯撒移用C [英] Simple Caesar shift in C

查看:153
本文介绍了简单凯撒移用C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图创建一个简单的凯撒用C转向计划,但我不能似乎看着办吧。该计划不断崩溃。任何帮助将大大AP preciated。

 的#include<&stdio.h中GT;
#包括LT&;&stdlib.h中GT;
#包括LT&;&string.h中GT;INT主(INT弧线,为const char * argv的[])
{
    INT移位=的atoi(ARGV [1]);
    CHAR消息[256];
    的strcpy(消息,的argv [2]);
    INT I;
    对于(i = 0; I< strlen的(消息),我++){
        的printf(%C,消息[I] +移);
    }
    的putchar('\\ n');
    返回0;
}


解决方案

你没有正确地实现凯撒密码。您code包括以下线,这是错误的:

 的printf(%C,消息[I] +移);

要正确地做到这一点,你需要将其转换成一个功能:

 的printf(%C,加密(消息[I],移));

和让我们来实现该功能:

 字符加密(字符输入,INT移){
    如果(输入> ='A'和;&安培;输入< ='Z')
        回报((输入 - 'A'+移动)26%)+'A';
    如果(输入> ='A'和;&安培;输入< ='Z')
        回报((输入 - 'A'+移)%26)+'A';
    返回输入;
}

而只是为了说明什么是数学在功能做的:


  1. 输入 - '一'告诉我们在什么位置字母的输入(假设输入小写字母)。因此,如果输入的是'C',那么我们将得到一个 2 回来。如果输入'Z',我们得到 25

  2. 输入 - 'A'+移得到我们,我们用做密码的字符的新位置。注意,这可能比字母表(26个字符)更大的数字。

  3. 所以要解决这个问题,我们使用模运算来约束这个数字之间的 [0 - 25]

  4. 然后添加'a'到那个角色获得我们,我们要打印的实际字符。

请注意,这只是工作,因为该字符codeS为 A 以Z A 以Z 是连续的。

I'm trying to create a simple Caesar shift program in C but I can't seem to figure it out. The program keeps crashing. Any help would be greatly appreciated.

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

int main(int arc, const char* argv[])
{
    int shift = atoi(argv[1]);
    char message[256];
    strcpy(message, argv[2]);
    int i;
    for(i = 0; i < strlen(message); i++) {
        printf("%c", message[i] + shift);
    }
    putchar('\n');
    return 0;
}

解决方案

You're not correctly implementing the Caesar Cipher. Your code includes the following line, which is wrong:

printf("%c", message[i] + shift);

To do this correctly, you'll want to convert that to a function:

printf("%c", encrypt(message[i], shift));

And let's implement the function:

char encrypt(char input, int shift) {
    if (input >= 'a' && input <= 'z')
        return ((input - 'a' + shift) % 26) + 'a';
    if (input >= 'A' && input <= 'Z')
        return ((input - 'A' + shift) % 26) + 'A';
    return input;
}

And just to explain what the math is doing in that function:

  1. input - 'a' tells us what position in the alphabet the input is (assuming input is a lowercase letter). So if the input is 'c', then we will get a 2 back. If the input is 'z', we get 25.
  2. input - 'a' + shift gets us the new position of the character that we are using to do the cipher. Note that this could be a larger number than the alphabet (26 characters).
  3. So to solve that problem, we use modular arithmetic to bound that number between [0 - 25].
  4. Then adding 'a' to that character gets us the actual character we want to print.

Note that this only works because the character codes for a to z and A to Z are consecutive.

这篇关于简单凯撒移用C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆