使用函数模板实现对不同类型数组求平均值的功能,并在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; }
这道题你会答吗?花几分钟告诉大家答案吧!
扫描二维码,关注牛客网
下载牛客APP,随时随地刷题