编辑代码

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

#define MAX_LEN 1000

void caesar_encrypt(char* plain, char* cipher, int key) {
    int i;
    for (i = 0; plain[i] != '\0'; i++) {
        if (plain[i] >= 'A' && plain[i] <= 'Z') {
            cipher[i] = ((plain[i] - 'A' + key) % 26) + 'A';
        } else if (plain[i] >= 'a' && plain[i] <= 'z') {
            cipher[i] = ((plain[i] - 'a' + key) % 26) + 'a';
        } else {
            cipher[i] = plain[i];
        }
    }
    cipher[i] = '\0';
}

void caesar_decrypt(char* cipher, char* plain, int key) {
    int i;
    for (i = 0; cipher[i] != '\0'; i++) {
        if (cipher[i] >= 'A' && cipher[i] <= 'Z') {
            plain[i] = (((cipher[i] - 'A') - key + 26) % 26) + 'A';
        } else if (cipher[i] >= 'a' && cipher[i] <= 'z') {
            plain[i] = (((cipher[i] - 'a') - key + 26) % 26) + 'a';
        } else {
            plain[i] = cipher[i];
        }
    }
    plain[i] = '\0';
}

int main() {
    char plain[MAX_LEN], cipher[MAX_LEN], decrypted[MAX_LEN];
    int key;

    printf("Enter the text to be encrypted: ");
    fgets(plain, MAX_LEN, stdin);

    printf("Enter the encryption key (1-25): ");
    scanf("%d", &key);

    caesar_encrypt(plain, cipher, key);
    printf("Encrypted text: %s\n", cipher);

    caesar_decrypt(cipher, decrypted, key);
    printf("Decrypted text: %s\n", decrypted);

    return 0;
}