⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 main.cpp

📁 表达式计算的代码 C C 表达式计算 字符串计算
💻 CPP
字号:
// Main.cpp: implementation of the CMain class.
//
//////////////////////////////////////////////////////////////////////

#include "Main.h"
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
using namespace std;
using namespace std;
//////////////////////////////////////////////////////////////////////
// 构造函数/析构函数
//////////////////////////////////////////////////////////////////////

CMain::CMain()
{
}
CMain::~CMain()
{
}
//匹配字符
void CMain::match(char expectedToken)
{
    if(this->token == expectedToken) 
		token = getchar();//获取下一个字符
    else
		this->errorProcess();
}
//表达式
Node* CMain::expression(void)
{
    Node* tempLeft = term();  //左数据节点
	Node* op = NULL;    //操作符节点
	Node* tempRight;  //右数据节点
    while((this->token=='+')||(this->token=='-'))
	{
	    op = new Node(0,this->token,OPERATOR);//实例操作符结点
	    this->match(this->token);//验证字符
        tempRight=this->term();
	    op->leftChild = tempLeft;
	    op->rightChild = tempRight;
		tempLeft = op;
	}
    return tempLeft;
}
//构造树节点
Node* CMain::factor(void)
{
   Node* temp;
   if(this->token=='(')
   {
      this->match('(');
	  this->expression();
	  this->match(')');
   }
   else
   {
	   if(this->isDigital(this->token))
	   {
		   double temp1;
		   ungetc(this->token,stdin);
           scanf("%lf",&temp1);  //获得输入的数据
           temp=new Node(temp1,' ',NUMBER);
		   this->token =getchar();
	   }
	   else
	   {
		   this->errorProcess();
	   }
   }
   return temp;
}
//
Node* CMain::term(void)
{
    Node* tempLeft = factor();
	Node* tempRight;
	Node* op = NULL;
    while((token=='*')||(token=='/'))
    {
	    op = new Node(0,token,OPERATOR);
        match(token);
	    tempRight = factor();
        op->leftChild = tempLeft;
	    op->rightChild = tempRight;
	    tempLeft = op;
	}
    return tempLeft;
}
//判断字符是否为数字
int CMain::isDigital(char c)
{
	if(c<='9' && c >= '0')	
		return 1;
	else
		return 0;
}
//错误处理
void CMain::errorProcess(void)
{
   cout<<"语法错误!"<<endl;
   exit(1);//退出程序
} 
//程序入口点
int main()
{
  Tree *expressionTree = new Tree;//实例化表达式树对象
  CMain *cmain=new CMain;//实例化操作逻辑对象
  cout << "请输入算术表达式:";
  cmain->token = getchar();//从键盘缓冲区读取字符
  expressionTree->root = cmain->expression();//构造表达式语法树
  //显示语法树
  if(cmain->token=='\n')
  {
	   cout<< "表达式语法树为:" <<endl;
       expressionTree->displayTree();//显示树
  }
  double result = expressionTree->getResult();//计算表达式值
  cout<< "表达式的值为 "<<result<<endl;//输出值
  return EXIT_SUCCESS;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -