填空题
请补充fun函数,该函数的功能是:按’0’到’9’统计一个字符串中的奇数数字字符各自出现的次数,结果保存在数组num中。注意:不能使用字符串库函数。
例如:输入:”x=1123.456+0.909*bc”,结果为:1=2,3=1,5=1,7=0,9=2.
请勿改动主函数main和其他函数中的任何内容,仅在fun函数的横线上填入所编写的若干表达或语句。#include
#include
#define N 1000
void fun(char *tt, int num[])
{
int i, j;
int bb[10];
char *p = tt;
for (i=0; i<10; i++)
{
num[i] = 0;
bb[i] = 0;
} 来源:www.exam8.com
while (*p)
{
if (*p>='0' && *p<='9')
bb[*p-‘0’]++;
p++;
}
for (i=1, j=0; i<10; i=i+2, j++)
num[j]=bb[i];
}
main()
{
char str[N];
int num[10], k;
printf("\nPlease enter a char string:");
gets(str);
printf("\n*******The original string******\n");
puts(str);
fun(str, num);
printf("\n*******The number of letter******\n");
for (k=0; k<5; k++)
{
printf("\n");
printf("%d= %d ", 2*k+1, num[k]);
}
printf("\n");
}
参考答案:
*p或*p!=0或0!=*p
bb[*p-’0’]++或bb[*p-‘0’]+=1
num[j]=bb[i]
改错题
下列给定程序中,函数fun的功能是:找出100至n(不大于1000)之间三个位上的数字都相等的所有整数,把这些整数放在s所指数组中,个数作为函数值返回。
请改正函数fun中的错误,使它能得出正确的结果。
注意:不要改动main函数,不得增行或删行,也不得更改程序的结构!
#include
#define N 100
int fun(int *s, int n)
{
int i, j, k, a, b, c;
j = 0;
for (i=100; i
{
/********found********/
k = i;
a = k%10;
k /= 10;
/********found********/
b = k%10;
c = k/10;
if (a==b && a==c)
s[j++] = i;
}
return j;
}
main()
{
int a[N], n, num = 0, i;
do
{
printf("\nEnter n(<=1000): ");
scanf("%d", &n);
} while (n > 1000);
num = fun(a, n);
printf("\n\nThe result :\n");
for (i=0; i
printf("%5d", a[i]);
printf("\n\n");
}
参考答案:
k=n;改为k=I;
b=k/10;改为b=k%10;
编程题
编写一个函数,从传入的num个字符串中找出最长的一个字符串,传回该串地址(用****作为结束输入的标志)。
请勿改动主函数main和其他函数中的任何内容,仅在函数fun的花括号中秘编写的若干语句。
#include
#include
#include
char *fun(char (*a)[81],int num)
{int i;
char *max;
max=a[0];
for(i=0;i<=num;i++)
if(strlen(max)
max=a[i];
return max;
}
main()
{
char ss[10][81],*max;
int n,i=0;
FILE *out;
printf("输入若干个字符串:");
gets(ss[i]);
puts(ss[i]);
while(!strcmp(ss[i],"****")==0)
{
i++;
gets(ss[i]);
puts(ss[i]);
}
n=i;
max=fun(ss,n);
printf("\nmax=%s\n",max);
out=fopen ("out.dat", "w");
strcpy(ss[0], "Oh,");
strcpy(ss[1], "you");
strcpy(ss[2], "want");
strcpy(ss[3], "some");
strcpy(ss[4], "too?!?");
fprintf(out, "%s", fun(ss, 5));
fclose (out );
}
参考答案:
char *fun(char (*a)[81],int num)
{int i;
char *max;
max=a[0];
for(i=0;i<=num;i++)
if(strlen(max)
max=a[i];
return max;
}
更多精彩请关注读书人网计算机频道!