例8.10 有两个数组a、b,各有10个元素,将它们对应地逐个相比(即a[0]与b[0]比,a[1]与b[1]比……)。如果a数组中的元素大于b数组中的相应元素的数目多于b数组中元素大于a数组中相应元素的数目(例如,a[i]>b[i]6次,b[i]>a[i]3次,其中i每次为不同的值),则认为a数组大于b数组,并分别统计出两个数组相应元素大于、等于、小于的次数。
程序如下:
main()
{ int large(int x,int y); /* 函数声明 */
int a[10],b[10],i,n=0,m=0,k=0;
printf("enter array a∶\n");
for(i=0;i<10;i++)
scanf("%d",&a[i]);
printf("\n");
printf("enter array b∶\n");
for(i=0;i<10;i++)
scanf("%d",&b[i]);
printf("\n");
for(i=0;i<10;i++)
{if(large(a[i],b[i])==1)n=n+1;
else if(large(a[i],b[i])==0) m=m+1;
else k=k+1;}
printf("a\[i\]>b\[i\]%d times\na\[i\]=b\[i\]%d times\na\[i\]<b\[i\]%d times\n",n,m,k);
if(n>k) printf("array a is larger than array b\n");
else if (n<k) printf("array a is smaller than array b\n");
else printf("array a is equal to array b\n");
}
large(int x,int y)
{int flag;
if(x>y)flag=1;
else if(x<y)flag=-1;
else flag=0;
return(flag);
}
运行情况如下:
enter array a:
1 3 5 7 9 8 6 4 2 0
enter array b∶
5 3 8 9-1-3 5 6 0 4
a[i]>b[i] 4 times
a[i]=b[i] 1 times
a[i]<b[i] 5 times
array a is smaller than array b
程序如下:
main()
{ int large(int x,int y); /* 函数声明 */
int a[10],b[10],i,n=0,m=0,k=0;
printf("enter array a∶\n");
for(i=0;i<10;i++)
scanf("%d",&a[i]);
printf("\n");
printf("enter array b∶\n");
for(i=0;i<10;i++)
scanf("%d",&b[i]);
printf("\n");
for(i=0;i<10;i++)
{if(large(a[i],b[i])==1)n=n+1;
else if(large(a[i],b[i])==0) m=m+1;
else k=k+1;}
printf("a\[i\]>b\[i\]%d times\na\[i\]=b\[i\]%d times\na\[i\]<b\[i\]%d times\n",n,m,k);
if(n>k) printf("array a is larger than array b\n");
else if (n<k) printf("array a is smaller than array b\n");
else printf("array a is equal to array b\n");
}
large(int x,int y)
{int flag;
if(x>y)flag=1;
else if(x<y)flag=-1;
else flag=0;
return(flag);
}
运行情况如下:
enter array a:
1 3 5 7 9 8 6 4 2 0
enter array b∶
5 3 8 9-1-3 5 6 0 4
a[i]>b[i] 4 times
a[i]=b[i] 1 times
a[i]<b[i] 5 times
array a is smaller than array b