编写计算器程序,用c++程序语言。

请编写程序实现任意数学表达式求值计算器功能
说明:
(^)是乘方运算符,(#)是开方运算符,键入(S)清屏,键入(Q)退出。
负数运算以及错误警告。
如输入数学表达式: 例 6+(6+8/2*(8-5)^3)*2 =234
6*10-4%3+10.6^3 =1151.727
00011001&&10010001 =00010001
(6*3)&&0||4=1
即:从键盘输入一段 表达式,通过程序计算,可得表达式的结果
要求得完成:加+、减-、乘*、除/、余%、n次方(^乘方)、开n次方(#开方)、与&&、或||、非!、括号() 等几种运算的混合运算。

所有你列的运算都实现了,代码如下
#ifndef _CALCULARTOR_H
#define _CALCULARTOR_H

#include <iostream>
#include <string>
#include <cmath>
#include <ctype.h>
#include <cstdlib>
using namespace std;

struct OPRT{
int size;
int top;
char *elements;

OPRT(int sizeOprt){
size=sizeOprt;
elements=new char[sizeOprt];
top=-1;
}
~OPRT(){
delete [] elements;
}
bool empty(){
if(top==-1)
return true;
else
return false;
}
bool full(){
if(top >= size-1)
return true;
else
return false;
}
bool push(char x){
if(full())
return false;
top++;
elements[top]=x;
return true;
}
bool pop(char &x){
if(empty())
return false;
x=elements[top];
top--;
return true;
}
char gettop(){
char x;
x=elements[top];
return x;
}
};
struct OPRD{
int size;
int top;
double *elements;

OPRD(int size1){
size=size1;
elements=new double[size1];
top=-1;
}
~OPRD(){
delete [] elements;
}
bool empty(){
if(top==-1)
return true;
else
return false;
}
bool full(){
if(top >= size-1)
return true;
else
return false;
}
bool push(double x){
if(full())
return false;
top++;
elements[top]=x;
return true;
}
bool pop(double &x){
if(empty())
return false;
x=elements[top];
top--;
return true;
}
double gettop(){
double x;
x=elements[top];
return x;
}
};

int precede(char cStackTop,char cNew);
double operate(double a,char theta,double b);

#endif

//:This is the main function of calculator

#include "calculator.h"

bool bError = false;

int main(void)
{
const int iSizeOfStk = 20;
OPRD oprd(iSizeOfStk);
OPRT oprt(iSizeOfStk);
string sInExp;
string sOprd; //to get num from sInExp
double dOprd;

cout << "Please enter the expression ended with '=' :" << endl;
getline(cin,sInExp,'=');
sInExp = sInExp + "=";

oprt.push('=');

//calculat
for( int iLoopStart = 0; iLoopStart < sInExp.length(); )
{
if( bError ) //error in exp exit loop
break;

int iLoopEnd = iLoopStart;
if( isdigit(sInExp.at(iLoopStart) ) ) //num
{
bool hasDot = false;
for( ; iLoopEnd < sInExp.length(); iLoopEnd++) //get num
{
if( isdigit(sInExp.at(iLoopEnd)) == 0 ) //find . or end of num
{
if(sInExp.at(iLoopEnd) == '.')
{
hasDot = true;
}
else
{
sOprd.assign( sInExp, iLoopStart, iLoopEnd-iLoopStart );
if( hasDot )
{
dOprd = atof( sOprd.c_str() );
}
else
{
dOprd = atoi( sOprd.c_str() );
}
oprd.push( dOprd );
break;
}
}
}
}
else //oprt
{
int iPre = precede( oprt.gettop(),sInExp.at( iLoopEnd ) );
while( iPre < 0) //运算
{
char cTemp;
double numA,numB;
if( !(oprt.pop(cTemp) && oprd.pop(numB) && oprd.pop(numA) ) )
//未成功出栈
{
bError = true;
}
else
{
double dTemp = operate(numA,cTemp,numB);
oprd.push(dTemp);
}
iPre = precede( oprt.gettop(),sInExp.at( iLoopEnd ) );
}
if( iPre == 1 ) //push into stack oprt
{
oprt.push( sInExp.at( iLoopEnd ) );
}
else if( iPre == 0 ) //() or miss( or miss )
{
char cNow = sInExp.at( iLoopEnd );
if( (oprt.gettop() == cNow) && (oprt.gettop() == '=') && (oprd.top == 0) )
{
break; //finish
}
else if( (cNow == ')') && (oprt.gettop() == '(') )
{
char cTemp;
oprt.pop(cTemp);
}
else
{
bError = true;
}
}
iLoopEnd++;
}
iLoopStart = iLoopEnd;
}
if( !bError )
{
double dTemp;
oprd.pop(dTemp);
cout.setf(ios::fixed | ios::showpoint);
cout.precision(2); //需要几位小数就设为多少
cout << dTemp << endl;
cout.unsetf(ios::fixed); //取消设置输出格式
cout.unsetf(ios::showpoint);
}
else
{
cout << "ERROR IN INFIX NOTATION" << endl;
}

return 0;
}

//:This is the implementation of calculator

#include "calculator.h"

extern bool bError;

//return the precede of two oprd
int precede(char cStackTop,char cNew)
{
int level[8][9]={
//row: stacktop, col:new entered
// +, -, *, /, %, ^, (, ), =
{-1,-1, 1, 1, 1, 1, 1,-1,-1}, //+
{-1,-1, 1, 1, 1, 1, 1,-1,-1}, //-
{-1,-1,-1,-1,-1, 1, 1,-1,-1}, //*
{-1,-1,-1,-1,-1, 1, 1,-1,-1}, ///
{-1,-1, 1, 1,-1, 1, 1,-1,-1}, //%
{-1,-1,-1,-1,-1, 1, 1,-1,-1}, //^
{ 1, 1, 1, 1, 1, 1, 1, 0, 0}, //(
{ 1, 1, 1, 1, 1, 1, 1, 0, 0}}; //=
// -1 pop,1 push,0 check or finished

int dStackTop,dNew;

switch(cStackTop)
{
case '+':
dStackTop = 0;
break;
case '-':
dStackTop = 1;
break;
case '*':
dStackTop = 2;
break;
case '/':
dStackTop = 3;
break;
case '%':
dStackTop = 4;
break;
case '^':
dStackTop = 5;
break;
case '(':
dStackTop = 6;
break;
case '=':
dStackTop = 7;
break;
}
switch(cNew)
{
case '+':
dNew = 0;
break;
case '-':
dNew = 1;
break;
case '*':
dNew = 2;
break;
case '/':
dNew = 3;
break;
case '%':
dNew = 4;
break;
case '^':
dNew = 5;
break;
case '(':
dNew = 6;
break;
case ')':
dNew = 7;
break;
case '=':
dNew = 8;
break;
}

return level[dStackTop][dNew];
}
//end of precede

//calculat the result
double operate(double a,char theta,double b)
{
double temp;
switch(theta)
{
case '+':
return a+b;
case '-':
return a-b;
case '*':
return a*b;
case '/':
return a/b;
case '^':
if( a < 0 && b!=(int)b )
{
bError = true;
return -1;
}
temp=pow(a,b);
return temp;
case '%':
if( b!=(int)b || a!= (int)a)
{
bError = true;
return -1;
}
return (int)a%(int)b;
break;
default:
bError = true;
return -1;
}
}
//end of the operate追问

编译的时候有一个错误Cannot open include file: 'calculator.h': No such file or directory,怎么办呢?

追答

这个程序并不只一个文件,一共有三个,你得先建一个项目,然后把三个文件导进去,再编译

追问

可以给我讲详细点嘛?

追答

如果一个程序既有头文件(这个你应该知道吧?)又有源文件,你就得建一个项目,然后在项目中添加你需要的头文件和源文件,这个很基本,当然可能我这个程序复杂了点,你试着改一下吧

追问

可以给我说说操作过程吗?

温馨提示:内容为网友见解,仅供参考
第1个回答  2011-12-09
这是C++写的计算器,你可以运行试试
#include "iostream"
#include "string"
using namespace std;

//---------------------------------- Stack.h --------------------------
//定义Stack类
const maxsize=20;
enum Error_code { success, overflow, underflow };

template <class T>
class Stack {
public:
Stack();
bool empty() const;
bool full() const;
int size() const;
void clear();
Error_code top(T &item) const;
Error_code pop();
Error_code push(const T &item);
private:
int count;
T entry[maxsize];
};

template <class T>
Stack<T>::Stack() {
count=0;
}

template <class T>
bool Stack<T>::empty () const {
return count==0;
}

template <class T>
bool Stack<T>::full () const {
return count==maxsize;
}

template <class T>
int Stack<T>::size() const {
return count;
}

template <class T>
void Stack<T>::clear() {
count=0;
}

template <class T>
Error_code Stack<T>::top (T &item) const {
if (empty()) return underflow;
item= entry[count-1];
return success;
}

template <class T>
Error_code Stack<T>::pop () {
if (empty()) return underflow;
count--;
return success;
}

template <class T>
Error_code Stack<T>::push (const T &item) {
if (full()) return overflow;
entry[count++]=item;
return success;
}
//------------------------------------------额外函数------------------

bool user_says_yes()
{
int c;
bool initial_response = true;
do { // Loop until an appropriate input is received.
if (initial_response)
cout << " (y,n)? " << flush;
else
cout << "Respond with either y or n: " << flush;
do { // Ignore white space.
c = cin.get();
} while (c == '\n' || c ==' ' || c == '\t');
initial_response = false;
} while (c != 'y' && c != 'Y' && c != 'n' && c != 'N');
return (c == 'y' || c == 'Y');
}

//---------------------------------- Main Program ----------------------

Stack<char> sign;
Stack<double> num;
int set; // 判断程序中的异常,以便适时退出

void process(char c) { //计算两个数的 + - * / 运算
int k=0;
double a,b;
sign.pop();
if (num.top(b)==success){ //判断例外
num.pop();
if (num.top(a)==success) {
num.pop();
k=1;
}
}
if (k) {
switch (c) {
case '+': num.push(a+b); break;
case '-': num.push(a-b); break;
case '*': num.push(a*b); break;
case '/':
if (b==0) { //分母不能为0
set=4;
num.push(-1);
}
else
num.push(a/b);
break;
}
}
else {set=1;num.push(-1);}
}
//输入表达式
void get_command(string &str) {
cout<<"\n请输入要进行运算的表达式,包括\" +,-,*,/,=,(,)\"和数字,"<<endl
<<"例如:\" 3+2.5*(6-25/4)-8.32= \"."<<endl
<<"注意: 以数字开头,等号结尾,中间括号要匹配."<<endl;
cin>>str;
}
//求值 表达式
double do_command(const string &str) {
string s="";
double outcome=-1;
char c;
for (int i=0;str[i]!='\0';i++)
{
if (set!=0) break; //例外 则停止运行
while (1) { //分离数据与运算符
if (str[i]<='9' && str[i]>='0' || str[i]=='.') {
s+=str[i];
i++;
}
else {
if(s!="") {
if (num.push(atof(s.c_str ()))==overflow)
set=3;
s="";
}
break;
}
}
char ch= str[i];
switch (ch) { //处理运算的优先级,并注意例外抛出
case '*':
case '/':
if (sign.top(c)==success)
if(c=='*'||c=='/') process(c);
if (sign.push(ch)==overflow)
set=3;
break;
case '+':
case '-':
while (sign.top(c)==success) {
if (c!='(') process(c);
else break;
}
if (sign.push(ch)==overflow)
set=3;
break;
case '(':
if (sign.push(ch)==overflow)
set=3;
break;
case ')':
while (sign.top(c)==success) {
if (c!='(') process(c);
else break;
}
sign.pop();
break;
case '=':
while (sign.top(c)==success) {
if (c!='(') process(c);
else break;
}
break;
default: set=2;break;
}
}
if (num.size()==1 && sign.size()==0)
num.top(outcome);
else set=1;
if (set==0) cout<<"运算结果是:\n"<<endl; //出错时的错误信息
else {
outcome=-1;
if (set==1) cout<<"\n您输入的不匹配,有错误发生。Result lost!!"<<endl;
if (set==2) cout<<"\n您输入了非法字符 , 请重新输入,谢谢合作!"<<endl;
if (set==3) cout<<"\nStack is full, Lost result!!"<<endl;
if (set==4) cout<<"\n 分母为0,不能进行除法运算,出现溢出, Lost result!!"<<endl;
}
return outcome;
}
// 主程序main()
int main() {
do {
string str,s;
set=0;
get_command(str);
s=str;
if( str[0]=='-') str='0'+str; //处理表达式中的负号
for (int i=1;str[i]!='\0';i++) {
if (str[i]=='-' && str[i-1]=='(') {
str.insert (i,"0");
i++;
}
}
double out= do_command(str);
cout<<s<<out<<endl; //输出结果
num.clear(); //清空栈
sign.clear();
cout<<"\n还要计算其它的吗"<<flush;
}while (user_says_yes()); //允许多次执行运算
return 1;
}追问

第一个算式都计算不出来啊!

相似回答