用c++编写两个重载的函数,返回一个数组的均值
答案:2 悬赏:40 手机版
解决时间 2021-01-31 02:31
- 提问者网友:刺鸟
- 2021-01-30 23:11
用c++编写两个重载的函数,返回一个数组的均值
最佳答案
- 五星知识达人网友:忘川信使
- 2021-01-31 00:50
#include
using namespace std;
template
double average(T *src, int len) // T 会通用类型
{
double sum = 0;
for (int i = 0; i < len; i++)
sum += src[i];
return sum / len;
}
int main()
{
int n[] = {10, 1, 27, 43, 15};
cout << "average: " << average(n, 5) << endl;
float f[] = {10.2f, 1.5f, 2.7f, 4.3f, 1.5f};
cout << "average: " << average(f, 5) << endl;
double d[] = {10.2, 51.5, 20.7, 40.3, 1.5, -12.6, 5.64};
cout << "average: " << average(d, 7) << endl;
return 0;
}
using namespace std;
template
double average(T *src, int len) // T 会通用类型
{
double sum = 0;
for (int i = 0; i < len; i++)
sum += src[i];
return sum / len;
}
int main()
{
int n[] = {10, 1, 27, 43, 15};
cout << "average: " << average(n, 5) << endl;
float f[] = {10.2f, 1.5f, 2.7f, 4.3f, 1.5f};
cout << "average: " << average(f, 5) << endl;
double d[] = {10.2, 51.5, 20.7, 40.3, 1.5, -12.6, 5.64};
cout << "average: " << average(d, 7) << endl;
return 0;
}
全部回答
- 1楼网友:掌灯师
- 2021-01-31 01:30
先将数组所有元素累加起来,再除以数据长度。
#include
double average(double *x, int len)
{
double sum = 0;
for (int i = 0; i < len; i++) // 求总和
sum += x[i];
return sum/len; // 返回平均值
}
int main()
{
double num[] = {1, 2, 3, 4, 5};
printf("average = %lf\n", average(num, 5));
return 0;
}
我要举报
如以上问答信息为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
推荐资讯