問題:
One of the oldest known encryption techniques is the Caesar cipher,
attributed to Julius Caesar. It involves replacing each letter in a message with
another letter that is a fixed number of positions later in the alphabet. (If the
replace would go past the latter Z, the cipher “wraps around” to the beginning of
the alphabet. For example, if each letter is replaced by the letter two positions
after it, the Y would be replaced by A, and Z would be replaced by B.) Write a
program that encrypts a message using a Caesar cipher. The user will enter the
message to be encrypted and the shift amount (the number of positions by which
letters should be shifted):
Enter message to be encrypted: Go ahead, make my day.
Enter shift amount (1-25): 3
Encrypted message: Jr dkhdg, pdnh pb gdb.
Notice that the program can decrypt a message if the user enters 26 minus the
original key:
Enter message to be encrypted: Jr dkhdg, pdnh pb gdb.
Enter shift amount (1-25): 23
Encrypted message: Go ahead, make my day.
You may assume that the message does not exceed 80 characters. Characters
other than letters should be left unchanged. Lower-case letters remain
lower-case when encrypted, and uppter-case letter remain upper-case. [Hint: To
handle the wrap-around problem, use the expression ((ch – 'A') + n) % 26
+ 'A' to calculate the encrypted version of upper case letter, where ch stores
the letter and n stores the shift amount. (You will need a similar expression for
lower-case letters.]
我的打法是:
#include <stdio.h>
#include <stdlib.h>
#include<string.h>
int main(void)
{
int i,j,n,m;
char list[80],listn[80];
printf("Enter message to be encrypted:" );
scanf("%s",&list);
printf("Enter shift amount (1-25):" );
scanf("%d",&m);
printf("Encrypted message:" );
n=strlen(list); //n是算字數的
for(i=0;i<n;i++)
{
if(65<=list[i] && list[i]<=90){
if(65<=list[i]+m && list[i]+m<=90)
listn[i]=list[i]+m;
else if(list[i]+m>90)
listn[i]=list[i]+m-26;
}
else if(97<=list[i] && list[i]<=122){
if(97<=list[i]+m && list[i]+m<=122)
listn[i]=list[i]+m;
else if(list[i]+m>122)
listn[i]=list[i]+m-26;
}
else
listn[i]=list[i];
printf("%c",listn[i]);
}
printf("\n");
system("PAUSE");
return 0;
}