37、写一个程序,进行体操评分,依次输入10名评委所评分数,去除一个最高分和一个最低分,再算出平均分作为选手的得分
//写一个程序,进行体操评分,依次输入10名评委所评分数,
//去除一个最高分和一个最低分,再算出平均分作为选手的得分。
#include<iostream>
#include<stdlib.h>
using namespace std;
float get_Ave(int *arr)
{
int max, min, s=0;
int i,j;
max = arr[0];
min = arr[0];
for(i=1; i<10; i++)
{
if(max<arr[i])
max = arr[i];
}
for(j=1; j<10; j++)
{
if(min>arr[j])
min = arr[j];
}
for(i=0; i<10; i++)
{
s += arr[i];
}
//cout << max << "," << min << "," << s << endl;
return (s-max-min)/8.0;
}
int main()
{
int a[10]={0}, i;
for(i=0; i<10; i++)
cin >> a[i];
cout << get_Ave(a) << endl;
system("pause");
return 0;
}
38、写一函数,将一数组中的元素反转
//写一函数,将一数组中的元素反转
#include<iostream>
#include<stdlib.h>
using namespace std;
int reverse_arr(int arr[], int n)
{
int i=0, t;
//int &a;
//int &b = arr[n-1-i];
for(i=0; i<n/2; i++)
{
//int &a = arr[i];
//int &b = arr[n-1-i];
//t = a;
//a = b;
//b = t;
t = arr[i];
arr[i] = arr[n-1-i];
arr[n-1-i] = t;
}
for(i=0; i<n; i++)
cout << arr[i] << " ";
cout << endl;
return 0;
}
int main()
{
int i, a[6] = {1,2,3,4,5,6};
reverse_arr(a,6);
//cout << sizeof(a)/sizeof(a[0]) << endl;//求数组a长度
for(i=0; i<6; i++)
cout << a[i] << " ";
cout << endl;
system("pause");
return 0;
}
39、写一函数,在一个数组中找出最大元素的位置
//写一函数,在一个数组中找出最大元素的位置
#include<iostream>
#include<stdlib.h>
using namespace std;
int SearchMax(int a[], int n)
{
int i, j, max=a[0];
for(i=1; i<n; i++)
{
if(max<a[i])
{
max = a[i];
j = i;
}
}
return j+1;
}
int main()
{
int a[10] = {1,2,5,4,3,8,10,7,9,6};
cout << SearchMax(a,10) << endl;
system("pause");
return 0;
}
40、找出一个二维数组中的鞍点,即该元素在该行上最大,在该列上最小
//找出一个二维数组中的鞍点,即该元素在该行上最大,在该列上最小。
#include<iostream>
#include<stdlib.h>
using namespace std;
int main()
{
int i, j, k, max, min, t=0, s=0;
int a[3][3] = {3,2,1,4,5,6,9,8,1};
//max = min = a[0][0];
for(i=0; i<3; i++)
{
for(j=1; j<3; j++)
{
if(a[i][j]>a[i][t]) t=j;
}
//cout << i << "行最大元素:" << a[i][t] << endl;
for(k=1; k<3; k++)
{
if(a[k][t]<a[s][t]) s = k;
}
//cout << t << "列最小元素:" << a[s][t] << endl;
if(a[i][t] == a[s][t]) // if()后的表达式等号用"=="
{
cout << "该数组的鞍点为:" ;
cout << "a[" << s << "][" << t << "]:" << a[s][t] << endl;
}
}
//cout << a[1][1] << a[2][2] << endl;
system("pause");
return 0;
}
题目来源:50道C/C++编程练习题及答案
总结
1、引用必须初始化 int &a = x; 参考:C++之引用&的详解
2、题39参考代码中取最大元素思路:比较前两个数的大小,取最大值下标,后一个数再跟前两个数中的最大值比较,如此循环,取得最大值元素;
3、题40编程思路:用两个for()循环嵌套遍历二维数组,先求第一行的最大值,获得最大值的下标后求该列的最小值,如果最大值和最小值是同一个值则该值为数组的鞍点,求最大、最小元素方法参考题39;
思考
Q: 通过交换、赋值可以交换数组中的两个值,并且作用于函数内部和函数外部;交换两个变量却只作用于函数内部,为什么?两者不同之处是什么?
交换数组中的两个值与指针做形参的交换两个变量的函数有相似之处,有待深入了解数组与指针。