首页 > 试题广场 >

使用函数模板实现对不同类型数组求平均值的功能,并在main函

[问答题]

使用函数模板实现对不同类型数组求平均值的功能,并在main函数中分别求一个整型数组和一个浮点型数组的平均值。

推荐
#include <iostream>
using namespace std;
template <typename T>
double average( T *array,int size )
{
  T sum = 0;
   for( int i=0; i<size; i++ )
      sum += array[i];
   return sum / size;
 }
int main()
{
 int a[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
   double b[] = { 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9, 10 };
   cout << "Average of array a :" << average( a,10 ) << endl;
   cout << "Average of array b :" << average( b,10 ) << endl;
}

发表于 2018-05-07 15:27:24 回复(0)