目录
- 第一关:数组倒置
- 第二关:字符排序
- 第三关:找最长串
- 第四关:星号转移
第一关:数组倒置
程序功能是通过调用reverse()函数按逆序重新放置数组a中的元素值,请补全程序。
测试输入: 0 1 2 3 4 5 6 7 8 9
预期输出: 9 8 7 6 5 4 3 2 1 0
#include "stdio.h"
#define N 10
void reverse(int *p, int a, int b)
{
int c;
/***** 请在以下一行填写代码 *****/
while (a<b)
{
c=*(p+a);
/***** 请在以下一行填写代码 *****/
*(p+a)=*(p+b);
*(p+b)=c;
a++;
/***** 请在以下一行填写代码 *****/
b--;
}
}
int main()
{
int a[N], i;
for (i=0; i<N; i++)
/***** 请在以下一行填写代码 *****/
scanf("%d",&a[i]);
reverse(a, 0, N-1);//传入首元素地址,首元素下表,末元素下标
for (i=0; i<N; i++)
/***** 请在以下一行填写代码 *****/
printf("%d ",a[i]);
printf("\n");
return 0;
}
注意:p+1指向数组的下一个元素,而不是简单的使使指针变量p的值+1
第二关:字符排序
对某一个长度为7个字符的字符串, 除首、尾字符之外,要求对中间的5个字符按ASCII码降序排列
测试输入: CEAedca
预期输出: CedcEAa
#include <stdio.h>
#include <ctype.h>
#include <string.h>
int fun(char *s, int num)
{
char ch;
int i, j;
for(i = 1 ; i < num-1 ; i++)
for(j = i + 1 ; j < 6 ; j++)
{
/***** 请在以下一行填写代码 *****/
if(s[i]<s[j])
{
ch = *(s + j);
*(s + j) = *(s +i);
*(s + i) = ch;
}
}
}
int main()
{
char s[10];
scanf("%s",s);
/***** 请在以下一行填写代码 *****/
fun(s,7);
printf("%s",s);
return 0;
}
第三关:找最长串
本关任务:给定程序中函数fun的功能是从N个字符串中找出最长的那个串,并将其地址作为函数值返回。N个字符串在主函数中输入,并放入一个字符串数组中。请改正程序中的错误,使它能得出正确结果。注意:不要改动main函数,不得增行或删行,也不得更改程序的结构。
测试输入: a bb ccc dddd eeeee
预期输出:
The 5 string :
a
bb
ccc
dddd
eeeee
The longest string :
eeeee
#include <stdio.h>
#include <string.h>
#define N 5
#define M 81
/***** 以下一行有错误 *****/
char* fun(char (*sq)[M])
{
int i; char *sp;
sp=sq[0];
for(i=0;i<N;i++)
if(strlen(sp)<strlen(sq[i]))
sp=sq[i];
/***** 以下一行有错误 *****/
return sp;
}
int main()
{
char str[N][M], *longest; int i;
for(i=0; i<N; i++)
scanf("%s",str[i]);
printf("The %d string :\n",N);
for(i=0; i<N; i++)
puts(str[i]);
longest=fun(str);
printf("The longest string :\n");
puts(longest);
return 0;
}
第四关:星号转移
规定输入的字符串中只包含字母和*号。给定程序的功能是将字符串中的前导*号全部移到字符串的尾部。请将程序补充完整,使其能正确运行得出结果。
测试输入: ***abcd
预期输出: abcd***
#include <stdio.h>
void fun( char *a )
{
int i=0,n=0;
char *p;
p=a;
while (*p=='*')
{
n++; //统计字符串中前导*号的个数
p++;
}
while(*p)
{
a[i]=*p; //把前导*号之后的字符全部前移
i++;
p++;
}
while(n!=0)
{
a[i]='*'; //把统计*号个数补到字符串的末尾
i++;
n--;
}
a[i]='\0';
}
int main()
{
char s[81];
int n=0;
scanf("%s",s);
fun(s);
printf("The string after oveing: \n");
puts(s);
return 0;
}