编写函数fun,函数功能是计算并输出给定数组(长度为9)中每相邻两个元素之平均值的平方根之和。例如,给定数组中的9个元素依次为12.0 34.0 4.0 23.0 34.0 45.0 18.0 3.0 11.0 ,输出应为:s=35.951014。我这输出结果不对是为什么?
#include <iostream>
#include <cmath>
#include<iomanip>
using namespace std;
/*计算并输出给定数组(长度为9)中每相邻两个元素之平均值的平方根之和 */
double fun(double x[9])
{
int i,sum=0.0,aver;
for (i = 0;i < 9;i++)
{
if (i + 1 < 9)
{
aver = (x[i] + x[i + 1]) / 2;
sum = sum + sqrt(aver);
}
}
return sum;
}
int main()
{
double s, a[9] = { 12.0,34.0,4.0,23.0,34.0,45.0,18.0,3.0,11.0 };
int i;
cout << "\nThe original data is :\n";
for (i = 0;i < 9;i++)cout << fixed << setprecision(1) << " " << a[i] << " ";
cout << endl << " ";
s = fun(a);
cout << setprecision(6) << "s=" << s << "\n\n";
}