数组典型例题及参考答案

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

第7章数组

7-1输入一个正整数n(1≤n≤10),再输入n个整数

(1)输出最大数和最小数,并输出平均值。

(2)将最小数与第一个数交换,最大数与最后一个数交换,然后输出交换后的结果。

(3)输出所有比平均值大的数。

(4)找到最接近平均值的数。(提示:考虑差的绝对值)

/* 将最小数与第一个数交换,最大数与最后一个数交换*/

t=a[0];

a[0]=a[q];

a[q]=t;

t=a[N-1];

a[N-1]=a[p];

a[p]=t;

printf("After exchange: ");

for(i=0; i

printf("%d ", a[i]);

/* 输出所有比平均值大的数*/

printf("\nLarger than the average: ");

for(i=0; i

if(a[i]>ave)

printf("%d ", a[i]);

/* 找到最接近平均值的数*/

printf("\nThe number closest to the average is: ");

sub = a[0]>ave? a[0]-ave: ave-a[0];

p=0;

for(i=1; i

{ if( (a[i]>ave? a[i]-ave: ave-a[i]) < sub )

{ sub = a[i]>ave? a[i]-ave: ave-a[i];

p=i;

}

}

printf("%d.", a[p]);

}

Output

Please input 10 integers:

17 34 -11 2 5 10 7 -9 0 25 /* input */

The maximum is: 34, the minimum is: -11, the average is 8.00

After exchange: -11 25 17 2 5 10 7 -9 0 34

Larger than the average: 25 17 10 34

The number closest to the average is: 7

7-2输入一个日期(按照year-month-day格式),计算该日期为当年的第几天。

(提示:注意闰年)

(1)使用数组存储当年每个月应有的天数;(2)不使用数组完成;

printf("This date is the %dth day in the year.\n", total);

}

Output

Please input a date: (year-month-day) 2008-4-14↵/* input */

This date is the 105th day in the year.

7-3输入一个正整数n(1≤n≤10),再输入n个整数,将这n个整数从大到小排序,然后在已经排序后的数组中插入平均数(取整),保持数组的升序,将插入平均数后的数组输出。

(1)用冒泡法排序;

(2)用选择法排序。

#define N 11

main()

{ int a[N], n, i, j, t, k, ave=0;

/* 读入数据,计算平均值*/

printf("How many numbers you want to sort? ");

scanf("%d", &n);

printf ( "Please input %d numbers:\n", n );

for ( i = 0; i <= n-1; i++)

{ scanf ( "%d", &a[i] );

ave += a[i];

}

ave /= n;

/* 冒泡法排序*/

for ( i = 1; i <= n-1; i++ )

{ for ( j = 1; j <= n - i; j++ )

{ if ( a[j-1] < a[j] )

{ t = a[j-1];

a[j-1] = a[j];

a[j] = t;

}

}

}

for(i=0; i

{ if(a[i]>ave)

continue;

for(j=n; j>i; j--)

a[j]=a[j-1];

a[i]=ave;

break;

}

for ( i = 0; i <= n; i++ )

printf ( "%d ", a[i] );

}

Output

How many numbers you want to sort? 5↵/* input */

Please input 5 numbers:

17 34 -11 2 5↵/* input */

34 17 9 5 2 -11

7-4输入两个数组A和B(各5个元素),将其按照升序排序,然后将A和B合并到数组C中(合并的过程中保持升序,不要合并后再排序)。输出排序后的数组A、B和C。

Program

#define N 5

main()

{ int a[N], b[N], c[2*N], i, j, t, k;

printf("Please input array A (containing %d elements): ", N);

for (i=0; i

scanf("%d", &a[i]);

printf("Please input array B (containing %d elements): ", N);

for (i=0; i

scanf("%d", &b[i]);

/* 冒泡法排序*/

for ( i = 1; i < N; i++ )

{ for ( j = 1; j <= N - i; j++ )

{ if ( a[j-1] > a[j] )

相关文档
最新文档