C++中用函数指针实现分段函数f(x) y=x-1(x<=0), y=2x+3(0<x<=10) ,y=x的平方+3(10<=10) 谢谢了,

2025-02-22 15:46:32
推荐回答(2个)
回答1:

#include
using namespace std;
double f1(double x);
double f2(double x);
double f3(double x);
void diaoyong(double x,double(*pf)(double));
int main()
{
double x;
cin>>x;
if(x<=0)
{
diaoyong(x,f1);
}
else if(x> 0 && x<10)
{
diaoyong(x,f2);
}
else if(x >= 10)
{
diaoyong(x,f3);
}
return 0;
}
double f1(double x)
{
return x-1;
}
double f2(double x)
{
return 2*x+3;
}
double f3(double x)
{
return x*x+10;
}
void diaoyong(double x,double(*pf)(double))
{
cout<<(*pf)(x)<}

回答2:

#include
using namespace std;

int Fuction(const int&);
int main()
{
typedef int (*PFunc)(const int&);
PFunc pfunc = Fuction;
int x;
cin >> x;
cout << pfunc(x);
return 0;
}

int Fuction(const int &x)
{
if (x <= 0)
{
return ( x-1 );
}
else if (x <= 10)
{
return ( 2*x + 3 );
}
return (x*x + 3);
}