C++实现简易计算器

C++实现简易计算器

实现功能:加减乘除乘方开方六种基本运算
开方采用二分法完成,精度控制在0.0000001内
加减乘除其实没必要写函数,写函数是强迫症为了保证画风统一

#include<iostream>
#include<cstring>
#include<float.h>
using namespace std;

double myAdd(double x,double y){ //加法
	return x + y;
}

double myReduce(double x,double y){ //减法
	return x - y;
}

double myMultipy(double x,double y){ //乘法
	return x * y;
}

double myDivide(double x,double y){ //除法
	return x / y;
}

double myPower(double x,double n){ //乘方,只支持正整数幂
	double result = 1;
	if(n > 0 && n == (int)n){
		for(int i=0;i<n;i++){
			result = result*x;
		}
		return result;
	}else{
		cout<<"抱歉,简易计算器仅支持正整数的幂运算"<<endl;
	}

}

double myAbsolute(double x){
	if(x >= 0){
		return x;
	}else{
		return -x;
	}
}

double myRoot(double x,double n){ //开方运算
	if(n > 0 && n == (int)n){
		double mid,low,high;
		double pMid; //中值的n次方
		high = x;
		low = 0;
		for(;;){
			mid = (high + low) / 2;
			pMid = myPower(mid,n); //power mid
			if( (x == pMid) ||
				(myAbsolute(x - pMid) < 0.0000001)){
				break;
			}else if(x > pMid){
				low = mid;
				mid = (high + mid) / 2;
			}else{ // x < pMid
				high = mid;
				mid = (mid + low) / 2;
			}
		}
		return mid;
	}else{
		cout<<"抱歉,简易计算器仅支持正整数根的开方运算"<<endl;
	}
}

void calculate(){
	double left,right;
	string op;
	cout<<"请依次输入您的左运算数、运算符和右运算数"<<endl;
	cin>>left>>op>>right;
	if(op == "+"){
		cout<<myAdd(left,right)<<endl;
	}else if(op == "-"){
		cout<<myReduce(left,right)<<endl;
	}else if(op == "×"){
		cout<<myMultipy(left,right)<<endl;
	}else if(op == "÷"){
		cout<<myDivide(left,right)<<endl;
	}else if(op == "^"){
		cout<<myPower(left,right)<<endl;
	}else if(op == "√"){
		cout<<myRoot(right,left)<<endl;
	}else{
		cout<<"抱歉,简易计算器暂不支持这种运算"<<endl;
	}
}

int main(){
	while(1){
		calculate();	
	}
}
上一篇:tp6微信公众号开发者模式基础消息


下一篇:2021SC@SDUSC Zxing开源代码(六)图像解码处理