Topic 6-1
- Algorithm: Define an array, month 1-12, and assign *month[n] according to the incoming n
- code
char getmonth( int n ){
char month[12]={"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
if(n>=1 && n<=12)
return month[n-1];
else
return NULL;
} - Errors that occurred: none
6-2
- Algorithm: Define an array of weeks, and then use a for loop to poll whether the incoming character group can correspond to the array of weeks. If it cannot be matched, return -1, if it can be matched, return the corresponding number of the week
- Code:
int getindex( char s ){
char weekday[7]={"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
int i=0;
int j=0;
for(;i<7;i++){
if(strcmp(s,weekday[i])==0){
return i;
j=1;}
}
if(j!=1)
return -1;
} - Error: segmentation fault; reason: array out of bounds; correction: modify the boundary value of i in for
6-3
- Algorithm: Define a maximum value, then poll the length of the incoming *s and the value of max, and finally return the max value
- Code:
int max_len( char *s[], int n ){
int num=0;
int t=0;
int max=0;
for(;t<n;t++){
num = strlen(s[t]);
if(max<num){
max=num;
}
}
return max;
} - Errors that occurred: none
6-4
forgot to write