【c++程序】函数指针

#include<iostream>
#include<string>
using namespace std;
float (*fp)(float&,float&);
void (*p)(float &,float &);
float triangle(float &x,float &y)
{
	return x*y*0.5;
}
float rectangle(float &x,float &y)
{
	return x*y;
}
void Swap(float &x,float &y)
{
	float n;
	n=x;
	x=y;
	y=n;
}
void print(float &x,float &y)
{
	cout<<"长"<<x<<"宽"<<y<<endl;
}
bool check(string str)
{
	for(int i=0;i<str.length();i++)
	{
		if((str[i]>'9'||str[i])<'0'&&(str[i]!='.'))//检测是否输入数字
			return false;
	}
	return true;
}
void get(float &x,float &y)
{
	cout<<"请输入x的新值";
	string str1;
	cin>>str1;
	while(!check(str1))
	{
		cout<<"输入的不是数字,请重新输入"<<endl;
		cin>>str1;
	}
	x=atof(str1.c_str());
	cout<<"请输入y的新值";
	string str2;
	cin>>str2;
	while(!check(str2))
	{
		cout<<"输入的不是数字,请重新输入"<<endl;
		cin>>str2;
	}
	x=atof(str2.c_str());
}
int main()
{
	bool quit=false;
	float a=2,b=3;
	int choice;
	while(quit==false)
	{
		cout<<"0-退出1-设定长和宽2-三角形3-长方形4-交换长和宽";
		cin>>choice;
		switch(choice)
		{
		case 1:cout<<"设定前长和宽的值";
			/*print(a,b);
			get(a,b);
			cout<<"设定后长和宽的值";
			print(a,b);*/
			p=get;
			break;
		case 2://print(a,b);
			cout<<"三角形的面积为";
				//<<triangle(a,b)<<endl;
			fp=triangle;
			break;
		case 3://print(a,b);
			cout<<"长方形的面积为";
				//<<rectangle(a,b)<<endl;
			fp=rectangle;
			break;;
		case 4:cout<<"交换前长和宽的值";
			/*print(a,b);
			swap(a,b);
			cout<<"设定后长和宽的值";
			print(a,b);*/
			p=Swap;
			break;
		default:
			quit=true;
			break;
		}
		if(choice==1||choice==4)
		{
			print(a,b);
			p(a,b);
			print(a,b);
		}
		else if(choice==2||choice==3)
		{
			print(a,b);
			cout<<"面积为"<<fp(a,b)<<endl;
		}
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值