#include<stdio.h>
#include<ctype.h> //区分大小写
#define MAX 100
char changeplus(char, int);//加上key个
char changeback(char, int);//减去key个
void fun(char (*)(char, int), char[]);
int main() {
char v[MAX]; //实参
char (*pc)(char, int); //声明一个pc,名字不重要,只要放在fun里面就好。为了方便,依然叫pc
fun( (*pc), v); //声明fun时把参数类型写全,这时候直接写上名字即可
printf("%s", v);//打印
return 0;
}
char changeplus(char character, int key){
if(islower(character)){ //如果他是一个小写字母
if(character + key <= 'z')
return character + key;
else
return 'a' + (key - ('z' - character) - 1);
}/*算法, 剩下的都大同小异, 如果没有越过边界,直接reutrn,否则就这样*/
else{
if(character + key <= 'Z')
return character + key;
else
return 'Z' + (key - ('Z' - character) - 1);/*算法*/
}
}
char changeback(char character, int key){
if(islower(character)){
if(character - key >= 'a')
return character - key;
else
return 'z' - (key - (character - 'a') - 1);
}
else
if(character - key >= 'A')
return character - key;
else
return 'Z' - (key - (character - 'Z') - 1);
}/*都差不多*/
void fun(char (*pc)(char , int), char s[]){ /*函数指针,即指向函数的指针*/
int sign, key; /*sign,判断加上或者减去*/ /*老师要求我们不要把main函数写的太臃肿,尽量把事情放的函数里做*/
scanf("%d%d", &sign, &key); //key,判断几个字符
pc = (sign == 1) ? changeplus : changeback; //网页里有介绍,p声明时只要格式相同,它就可以指向与他类型相同的函数,/*即为sign为一,加上,sign为0,减去*/
int i = 0;
int ch;
while((ch = getchar())!= EOF){
s[i] = (*pc)(ch, key);//每读到一个字符就用函数pc作用一下储存到形参s中
++i;
}
}
凯撒密码,用到了函数指针
最新推荐文章于 2024-08-19 10:16:30 发布