在C中使用简单的Cesar密码

在C中使用简单的Cesar密码,c,encryption,caesar-cipher,C,Encryption,Caesar Cipher,我在大学的一个项目中工作,他们使用了一个类似于典型的塞萨尔密码的问题。它更像是一个功能性程序,需要尽可能是最基本的 程序将从用户处接收一个从65到90的数字,例如,当用户插入65时,程序将显示68。将添加3数字,但当用户给出90时,将给出6790+3-->90,65,66,67。这是一个从65到90的循环 #include <stdio.h> int cesar_encrypted(int x) { return (x+3); } void test_cesar_encry

我在大学的一个项目中工作,他们使用了一个类似于典型的塞萨尔密码的问题。它更像是一个功能性程序,需要尽可能是最基本的

程序将从用户处接收一个从
65
90
的数字,例如,当用户插入
65
时,程序将显示
68
。将添加
3
数字,但当用户给出
90
时,将给出
67
<代码>90+3-->90,65,66,67。这是一个从
65
90
的循环

#include <stdio.h>

int cesar_encrypted(int x)
{
  return (x+3);
}


void test_cesar_encrypted(void)
{
    int x;
    scanf("%d", &x);
    int z = cesar_encrypted(x);
    printf("%s\n", z);
}

int main(){
    test_cesar_basic();

}
#包括
int cesar_加密(int x)
{
返回(x+3);
}
无效测试已加密(无效)
{
int x;
scanf(“%d”和&x);
int z=cesar_加密(x);
printf(“%s\n”,z);
}
int main(){
test_cesar_basic();
}
我做了这个示例代码,但我们只能更进一步,如果你给出
90
,他会给出
93
,我想要
67


有人能帮我把它围成90吗?

使用模运算
%
来定义所需间隔的上限和 然后使用加法
+
定义下限:

int cesar_encrypted(int x)
{ 
   // to wrap around 90  
   int encrypted = (x - 65 +3) % (90 - 65);
   // to start from 65, translate it adding 65  
   encrypted +=65;
   return encrypted;
}
或者在一行中:

int cesar_encrypted(int x){  
   return  (x - 65 + 3) % (90 - 65)  + 65; // x in range [65,90]
}

您可以使用模运算符,它给出除法的余数:

int cesar_encrypted(int x)
{
  return (x - 65 + 3)%(91 - 65) + 65;
}

执行Sulthan的建议(见评论),情况如下:

int cesar_encrypted(int x)
{
  const int n_chars = 'Z' - 'A' + 1;
  const int shift = 3;
  return (x - 'A' + shift)%n_chars + 'A';
}

如果
x+3>90
,只需换行到65,否则不执行任何操作:

int cesar_encrypted(int x)
{
    return (x+3 > 90 ? ((x+3) % 90 + 64) : x+3);
}
您可以在这里看到它的工作原理:
当然,您可以简化这个,使代码没有if语句(如其他ppl所述):


除此之外,代码中还有一些小的拼写错误。这里有一个类型不匹配:

int z = cesar_encrypted(x);
printf("%s\n", z); // you are trying to print a string instead of int

首先,让我们定义一些常量以使代码更具可读性:

const int MIN_CHAR = 'A'; //equivalent to 65
const int MAX_CHAR = 'Z'; //equivalent to 90
const int NUM_CHARS = MAX_CHAR - MIN_CHAR + 1; //how many chars we have
const int SHIFT = 3; //how many characters we shift when ecrypting
现在

也可以使用模块运算符作为

int cesar_encrypted(int x) {
    return (x + SHIFT - MIN_CHAR) % NUM_CHARS + MIN_CHAR;
}

90-65=25
。但它应该是模数26,因为字母表中有26个字符。无论如何,这对他做作业来说已经足够了。我会用
'A'
代替65,用
'Z'
代替90。另外,定义一个常量
const int numCharacters='Z'-'a'+1
可以稍微简化它。结果:
return(x-'A'+shift)%numCharacters+'A'
。我担心他希望程序是“最基本的”,先生。@MateuszKwasniak,如果你认为“short”比你的错误更“基本”。我不这么认为,但是我认为没有必要通过声明const变量来使代码变得非常清晰(当然,它看起来更好,更具可定制性,但我相信这只是一个家庭作业)。@MateuszKwasniak我编写的每个程序都像生产代码一样。对我来说,没有什么比“这只是一个家庭作业”、“这只是一个单元测试”更重要的了我认为我们应该一直努力使程序更具可读性。学生们尤其应该学会如何做。是的,我更喜欢基础,因为我还没有学其他东西!我是编程新手,C新手。
int cesar_encrypted(int x) {
    if (x + SHIFT > MAX_CHAR) {
        return x + SHIFT - NUM_CHARS; //just subtract the number of chars.
    }

    return x + SHIFT;
}
int cesar_encrypted(int x) {
    return (x + SHIFT - MIN_CHAR) % NUM_CHARS + MIN_CHAR;
}