ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

C++实现简易计算器

2022-02-05 11:04:30  阅读:160  来源: 互联网

标签:return double mid C++ high 简易 low 计算器 pMid


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();	
	}
}

标签:return,double,mid,C++,high,简易,low,计算器,pMid
来源: https://www.cnblogs.com/Ding1fun/p/15863917.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有