凯撒密码c语言pta
时间: 2024-05-27 08:06:09 浏览: 254
凯撒密码是一种简单的加密方法,它的原理是将明文中的每个字母按照字母表顺序向后移动固定的位数来加密。比如,将明文中的每个字母向后移动3位,则"A"会变成"D","B"会变成"E",以此类推。加密后的密文可以通过将每个字母向前移动同样的位数来解密。
在C语言中实现凯撒密码,可以通过以下步骤实现:
1. 读取明文和密钥(即向后移动的位数);
2. 将明文中的每个字母按照密钥向后移动相应的位数,并将结果存储到一个新的字符串中;
3. 输出加密后的密文。
下面是一个示例程序:
```c
#include <stdio.h>
#include <string.h>
int main()
{
char plaintext[100], ciphertext[100];
int i, key;
printf("请输入明文:");
gets(plaintext);
printf("请输入密钥(向后移动的位数):");
scanf("%d", &key);
for (i = 0; plaintext[i] != '\0'; i++)
{
if (plaintext[i] >= 'a' && plaintext[i] <= 'z')
{
ciphertext[i] = 'a' + (plaintext[i] - 'a' + key) % 26;
}
else if (plaintext[i] >= 'A' && plaintext[i] <= 'Z')
{
ciphertext[i] = 'A' + (plaintext[i] - 'A' + key) % 26;
}
else
{
ciphertext[i] = plaintext[i];
}
}
ciphertext[i] = '\0';
printf("加密后的密文为:%s\n", ciphertext);
return 0;
}
```
阅读全文
相关推荐















