2

我在大学的一个项目中工作,他们使用了典型的 Cesar Cipher 之类的问题。它更像是一个函数式程序,需要尽可能地是最基本的。

该程序将从用户那里收到一个数字6590例如当用户插入时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_encrypted(void)
{
    int x;
    scanf("%d", &x);
    int z = cesar_encrypted(x);
    printf("%s\n", z);
}

int main(){
    test_cesar_basic();

}

我做了这个示例代码,但我们只能走得更远,如果你给90他会给93我想要67的。

谁能帮我把它包装在90左右?

4

4 回答 4

4

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

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';
}
于 2015-09-23T10:15:07.863 回答
1

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

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) {
    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;
}
于 2015-09-23T10:38:49.803 回答
1

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

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]
}
于 2015-09-23T10:09:38.123 回答
0

只需换行到 65 if x+3 > 90,否则什么也不做:

int cesar_encrypted(int x)
{
    return (x+3 > 90 ? ((x+3) % 90 + 64) : x+3);
}

你可以在这里看到它是如何工作的:http: //ideone.com/sunxTb
当然,你可以简化它以拥有一个没有 if 语句的代码(正如其他 ppl 提到的):

return (x - 65 + 3)%(91 - 65) + 65;

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

int z = cesar_encrypted(x);
printf("%s\n", z); // you are trying to print a string instead of int
于 2015-09-23T10:15:11.813 回答