凯撒密码的原理是字母与字母之间的替换。例如26个字母都向后移动K位。若K等于2,则A用C代替,B用D代替,以此类推。
#include stdio.h
#include conio.h
int main(){
int key;
char mingma,mima;
printf("\nPlease input the character:");
scanf("%c",mingma); //输入明码
printf("\nPlease input the key:");
scanf("%d",key); //输入秘钥
if((mingma='A')(mingma='Z'))
mima='A'+(mingma-'A'+key)%26; //大写字母移位
else if((mingma='a')(mingma='z'))
mima='a'+(mingma-'a'+key)%26; //小写字母移位
printf("\n The output is:%c",mima); //输出密码
printf("\nFinished!\n");
getch();
return 0;
}
#includestdio.h
#includestring.h
void main ()
{
char str[100];
char str1[100];
printf("输入字符串:");
scanf("%s",str);
int len;
len=strlen(str);
for(int i=0;i<len;i++)
{
str1[i]=(str[i]-97+3)%26+97;
}
str1[len]='\0';
printf ("密文为:%s\n",str1);
}
#include stdio.h
#define isletter( c ) ( ((c)='a'(c)='z') || ((c)='A'(c)='Z') )
void Enc( const char *str, char *out, int key )
{
int i = 0;
while( str[i] )
{
if ( isletter( str[i] ) )
{
out[i] = str[i] + key;
if ( ! isletter( out[i]) )
out[i] -= 26;
}
else
out[i] = str[i];
i++;
}
out[i] = 0;
}
void Denc( const char *str, char *out, int key )
{
int i=0;
while( str[i] )
{
if ( isletter( str[i] ) )
{
out[i] = str[i] - key;
if ( ! isletter( out[i] ) )
out[i] += 26;
}
else
out[i] = str[i];
i++;
}
out[i] = 0;
}
int main()
{
char out[100], out2[100];
Enc( "THE QUICK BROWn fox jumps over THE LAZY DOG", out, 3 );
printf( "%s\n", out );
Denc( out, out2, 3 );
printf( "%s\n", out2 );
}