使用C++编写程序:
题目描述
已知:y是x的函数, 当x<-2时,y=7-2x; 当x>=-2,且x<3时,y=5-|3x+2|; 当x>=3时,y=3x+4
输入
任意输入一个整数x。
输出
输出为一个整数,即x对应的函数值。
样例输入 Copy
2
样例输出 Copy
-3
程序代码如下:
#include<iostream>
#include<iomanip>
//#include<vector> //顺序容器vector(向量)的头文件
#include<cmath>
#define ElemType_D double
using namespace std;
class PFEvaluation
{
public:
PFEvaluation(ElemType_D X) :x(X) {};
void GetValue();
private:
ElemType_D x;
};
inline void PFEvaluation::GetValue()
{
if (x < -2)
cout << fixed << setprecision(0) << 7 - 2 * x;
else if (x < 3)
cout << fixed << setprecision(0) << 5 - abs(3 * x + 2);
else
cout << fixed << setprecision(0) << 3 * x + 4;
}
/*
class PFEvaluation
{
public:
PFEvaluation(ElemType_D X);
void GetValue();
private:
vector<ElemType_D> x;
};
inline PFEvaluation::PFEvaluation(ElemType_D X)
{
x.push_back(X); //向容器内存入元素
}
inline void PFEvaluation::GetValue()
{
if (x[0] < -2)
cout << fixed << setprecision(0) << 7 - 2 * x[0];
else if (x[0] < 3)
cout << fixed << setprecision(0) << 5 - abs(3 * x[0] + 2);
else
cout << fixed << setprecision(0) << 3 * x[0] + 4;
}
*/
int main()
{
ElemType_D x;
cin >> x;
PFEvaluation PFE(x);
PFE.GetValue();
return 0;
}