大家在编c++程序时有没有想过在c++中实现不同类型的数实现加减乘除?今天就用c++11里的auto和decltype来实现!
一,计算两个未知类型的数的加减乘除
我们可以利用 auto 关键字将返回类型后置
template<typename PLL,typename MSD>
auto Plus(PLL a,MSD b) -> decltype(a+b){//拖尾返回类型:auto (name)() -> decltype()
return a+b;
}
减乘除也一样:
template<typename PLL,typename MSD>//减
auto Sub(PLL a,MSD b) -> decltype(a-b){
return a-b;
}
template<typename PLL,typename MSD>//乘
auto Time(PLL a,MSD b) -> decltype(a*b){
return a*b;
}
template<typename PLL,typename MSD>//除
auto Low(PLL a,MSD b) -> decltype(a/b){
return a/b;
}
二,读入未知类型的数
大家可能想过使用auto来解决一切,可下面这种写法是不被允许的(编译失败):
int main(){
auto x,y;
cin>>x>>y;
cout<<x+y<<endl;
}
那我们就得用string来解决
double getnum(string n){
int pointplace;
bool ifdouble=false;
for(int i=0;i<=n.size()-1;i++){
if(n[i]=='.'){
ifdouble=true;
pointplace=i;
}
}
if(ifdouble==false){
int cur=1,sum=0;
for(int i=n.size()-1;i>=0;i--){
sum+=cur*(n[i]-48);
cur*=10;
}
return sum*1.0;
}
else
{
int cur=1;
double sum=0,smallcur=0.1;
for(int i=pointplace-1;i>=0;i--){
sum+=cur*(n[i]-48)*1.0;
cur*=10;
}
for(int i=pointplace+1;i<=n.size()-1;i++){
sum+=smallcur*(n[i]-48);
smallcur=smallcur/10;
}
return sum;
}
}
三,总程序
#include<bits/stdc++.h>
using namespace std;
template<typename PLL,typename MSD>
auto Plus(PLL a,MSD b) -> decltype(a+b){//拖尾返回类型:auto (name)() -> decltype()
return a+b;
}
template<typename PLL,typename MSD>//减
auto Sub(PLL a,MSD b) -> decltype(a-b){
return a-b;
}
template<typename PLL,typename MSD>//乘
auto Time(PLL a,MSD b) -> decltype(a*b){
return a*b;
}
template<typename PLL,typename MSD>//除
auto Low(PLL a,MSD b) -> decltype(a/b){
return a/b;
}
double getnum(string n){
int pointplace;
bool ifdouble=false;
for(int i=0;i<=n.size()-1;i++){
if(n[i]=='.'){
ifdouble=true;
pointplace=i;
}
}
if(ifdouble==false){
int cur=1,sum=0;
for(int i=n.size()-1;i>=0;i--){
sum+=cur*(n[i]-48);
cur*=10;
}
return sum*1.0;
}
else
{
int cur=1;
double sum=0,smallcur=0.1;
for(int i=pointplace-1;i>=0;i--){
sum+=cur*(n[i]-48)*1.0;
cur*=10;
}
for(int i=pointplace+1;i<=n.size()-1;i++){
sum+=smallcur*(n[i]-48);
smallcur=smallcur/10;
}
return sum;
}
}
int main(){
while(true){
string x,y;
cin>>x>>y;
cout<<"加: "<<Plus(getnum(x),getnum(y))<<endl<<"减: "<<Sub(getnum(x),getnum(y))<<endl<<"乘: "<<Time(getnum(x),getnum(y))<<endl<<"除: "<<Low(getnum(x),getnum(y))<<endl<<endl<<endl;
}
}