习题11-1 输出月份英文名 (15 分)
本题要求实现函数,可以返回一个给定月份的英文名称。
函数接口定义:
char *getmonth( int n );
函数getmonth应返回存储了n对应的月份英文名称的字符串头指针。如果传入的参数n不是一个代表月份的数字,则返回空指针NULL。
裁判测试程序样例:
#include <stdio.h>
char *getmonth( int n );
int main()
{
int n;
char *s;
scanf("%d", &n);
s = getmonth(n);
if ( s==NULL ) printf("wrong input!\n");
else printf("%s\n", s);
return 0;
}
/* 你的代码将被嵌在这里 */
输入样例1:
5
输出样例1:
May
输入样例2:
15
输出样例2:
wrong input!
代码:
/*使用指针数组,让数组中的每一个元素都是指针变量,当满足某个条件时,就直接进行指针变量之间的赋值*/
char *getmonth( int n ){
char *month[12] = {"January","February","March","April","May","June","July","August","September","October","November","December"};
char *p = NULL;
int i;
for(i=0;i<12;i++){
if(i+1==n){
p = *(month + i);
//或者这种:p = month[i];
break;
}
}
return p;
}
与上述题型类似的还有一个例子:
函数接口定义:
int getindex( char *s );
函数getindex应返回字符串s序号。如果传入的参数s不是一个代表星期的字符串,则返回-1。
裁判测试程序样例:
#include <stdio.h>
#include <string.h>
#define MAXS 80
int getindex( char *s );
int main()
{
int n;
char s[MAXS];
scanf("%s", s);
n = getindex(s);
if ( n==-1 ) printf("wrong input!\n");
else printf("%d\n", n);
return 0;
}
/* 你的代码将被嵌在这里 */
输入样例1:
Tuesday
输出样例1:
2
输入样例2:
today
输出样例2:
wrong input!
代码:
/*同样使用了指针数组,可优化地方:直接使用char *day[7]*/
int getindex( char *s ){
char day[7][10] = {"Sunday", "Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"};
char *p[7];
int i;
for(i = 0;i<7;i++){
p[i]=day[i];
}
for(i = 0;i<7;i++){
if( strcmp(p[i],s)==0 )
return i;
}
return -1;
}