1035: 分段函数求值

54 篇文章 3 订阅

使用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;
}
程序运行结果如下:

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值