/*
1.根据公式计算y的值。
其中∑表示求各项的和,
∏表示求各项的积。
定义一个类F,实现上述功能。具体要求如下:
(1)私有数据成员
double x[5]: //存放xi(i = 1,2,3,4,5)的值,xi不能为0。
int n,k,h: //公式中对应的变量,n不能为0。
double y: //存放计算结果。
(2)公有成员函数
F(double a[], int _n, int _k, int _h): //构造函数,分别初始化x、n、k、h。
void calc(): //根据公式计算y的值。
(3)友元函数
void print(F f):输出对象f所有数据成员。
(4)在主函数中对该类进行测试。
测试数据
xi取3.2、 - 2.5、 - 4.2、3.6、5.2,
n取5,
k取3,
h取4,
测试结果y = 2.59513×1040。
注意公式中用到的函数(乘方、对数、绝对值、平方根)
请在头文件math.h中查找。
正确的输出结果如下:
3.2 - 2.5 - 4.2 3.6 5.2
5 3 4
2.59513e+040
*/
#include <iostream>
#include <windows.h>
#include <math.h>
using namespace std;
class F
{
private: //(1)私有数据成员
double x[5]; //存放xi(i = 1,2,3,4,5)的值,xi不能为0。
int n;
int k;
int h; //公式中对应的变量,n不能为0。
double y; //存放计算结果。
public: //(2)公有成员函数
F(double a[], int _n, int _k, int _h); //构造函数,分别初始化x、n、k、h。
void calc(); //根据公式计算y的值。
//(3)友元函数
friend void print(F f); // 输出对象f所有数据成员。
};
F::F(double a[], int _n, int _k, int _h)
{
for (int i = 0; i < 5; i++)
{
x[i] = a[i];
}
n = _n;
k = _k;
h = _h;
}
void F::calc()
{
double sum = 1;
double sum2 = 0;//一开始我用的1 不好意思,忘记是加了
for (int i = 0; i < n; i++)
{
sum *= pow(x[i], k)*log( fabs(x[i]) );
}
for (int i = 0; i < n; i++)
{
sum2 += pow(x[i], h);
}
sum = sum / sum2;
for (int i = 0; i < n; i++)
{
sum2 += sqrt( fabs(x[i]) );
}
sum2 = sum2 / n;
y = pow((sum - sum2) , (k + h));
}
void print(F f)
{
cout << "a[] = " << endl;
for (int i = 0; i < 5; i++)
{
cout << f.x[i] << " " << endl;
}
cout << "h = " << f.h << " " << endl;
cout << "n = " << f.n << " " << endl;
cout << "k = " << f.k << " " << endl;
cout << "y = " << f.y << " " << endl;
}
int main()
{
double x[5] = { 3.2, -2.5, -4.2, 3.6, 5.2 };
F f1(x,5,3,4);
f1.calc();
print(f1);
system("pause");
return 0;
}