当前位置:首页 » 编程软件 » 编译原理实现的计算器

编译原理实现的计算器

发布时间: 2022-09-02 18:26:17

‘壹’ 用java写的计算器的程序!不需要界面!

用java写的计算器的程序,主要是通过控制台输入,主要方法是使用scanner类来接收用户从键盘输入的一个算式,通过分解算式,存入两个字符串,判断中间的的符号,进行相应计算,如下代码:

System.out.println("-----------------------------------");
System.out.println("请输入一个算术表达式,如:45*23");
Scannerin=newScanner(System.in);//接收用户从键盘输入的字符
Stringstr=in.nextLine();
StringBufferbuffer=newStringBuffer();//保存左侧的数字
StringBufferbuffer1=newStringBuffer();//保存右侧的数字
chart='';//保存运算符
for(inti=0;i<str.length();i++){
if(str.charAt(i)=='+'||str.charAt(i)=='-'
||str.charAt(i)=='*'||str.charAt(i)=='/'){
t=str.charAt(i);//识别是什么运算符

for(intj=i+1;j<str.length();j++){
buffer1.append(str.charAt(j));
}
break;
}else{
buffer.append(str.charAt(i));
}
}
Stringc=buffer.toString();
Stringd=buffer1.toString();
doublea=Double.parseDouble(c);
doubleb=Double.parseDouble(d);
doublesum=0;
if(t=='+'){
sum=a+b;
}
if(t=='-'){
sum=a-b;
}
if(t=='*'){
sum=a*b;
}
if(t=='/'){
sum=a/b;
}
System.out.println("程序运算...");
System.out.println(c+t+d+"="+sum);
System.out.print("-----------------------------------");

运行结果如下:

‘贰’ 用c或c++编写一个具有计算器功能的程序,要求一次性输入一行要求算式,输入“=”输出结果,有什么好的思路

可以用2叉树写。

定义运算式结构体类型,比如:

typedefstructyunsuan
{
//如果是单一运算,比如1+2,那么num1=1;num2=2;
intnum1;//左儿子运算符为0的时候直接取该值
intnum2;//右儿子运算符为0的时候直接取该值,为NULL说明只有一个数值运算
structyunsuan*father;//父亲:如果上层还有运算式,指向上层
structyunsuan*brother;//兄弟:如果同级还有其他运算式,指向该运算式结构
//如果是复合运算,为其创建左儿子,右儿子,指向儿子,并让儿子指向父亲
structyunsuan*left;//左儿子
structyunsuan*right;//右儿子
charfh;//运算符号
}YS;

根据优先级解析多运算符的式子,比如2^2+(√4-1)。

从运算顺序最低的运算符号开始先找到'+',创建树顶点结构体,fh='+';father=NULL;brother=NULL;left=(2^2)的结构体;right=(√4-1)的结构体;

(2^2)的结构体:fh='^';num1=2;num2=2;father=最顶端的结构体;brother=(√4-1)的结构体;left=新建节点fh置0;right=新建节点fh置0;

(√4-1)的结构体:fh='-';num2=1;father=最顶端的结构体;brother=(2^2)的结构体;left=√4的结构体;right=新建节点fh置0;

√4的结构体:fh='√';num1=4;father=(√4-1)的结构体;brother=NULL;left=新建节点fh置0;right=NULL;

依次类推,以上只是说明树形结构建立。

你解析字符串,从运算顺序最后的字符开始拆分并创建树的最顶层节点,然后依次往下建立树。

最后可以用递归函数或循环,遍历树各节点进行运算。

‘叁’ (高分)求一个正确lex和yacc编的计算器(编译原理)

网上多的是,大多可以运行。关键是你要在Linux下分别将 lex和yacc文件用 flex 和 bison 编译成对应的c文件,然后在windows下用VC或者Codeblock的IDE下编写界面,连接刚才对应的c文件,生成exe交给老师。

‘肆’ 请教:用vc6.0编一个简单计算器的基本流程

我就不说界面了,光给个核心算法吧,支持表达式,比如(23+3*43)*2+4*(2+2)
原理?搜索关键词:编译原理,EBNF
/*
simple integer arithmetic calculator according to the EBNF
<exp> -> <term>{<addop><term>}
<addop>->+|-
<term>-><factor>{<mulop><factor>}
<mulop> -> *
<factor> -> ( <exp> )| Number
Input a line of text from stdin
Outputs "Error" or the result.
*/
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

char token;/*global token variable*/
/*function prototypes for recursive calls*/
int exp(void);
int term(void);
int factor(void);

void error(void)
{
fprintf(stderr,"Error\n");
exit(1);
}

void match(char expectedToken)
{
if(token==expectedToken)token=getchar();
else error();
}

main()
{
int result;
token = getchar();/*load token with first character for lookahead*/
result = exp();
if(token=='\n')/*check for end of line */
printf("Result = %d\n",result);
else error();/*extraneous cahrs on line*/
return 0;
}

int exp(void)
{
int temp = term();
while((token=='+')||(token=='-'))
switch(token)
{
case '+':
match('+');
temp+=term();
break;
case '-':
match('-');
temp-=term();
break;
}
return temp;
}

int term(void)
{
int temp = factor();
while (token=='*')
{
match('*');
temp*=factor();
}
return temp;
}

int factor(void)
{
int temp;
if(token=='('){
match('(');
temp = exp();
match(')');
}
else if(isdigit(token)){
ungetc(token,stdin);
scanf("%d",&temp);
token = getchar();
}
else error();
return temp;
}

‘伍’ 这个用C语言写的计算器的思路是什么

对初学编程者来说,这个程序的原理确实难了点,因为它用到了编译原理的知识.
即如果设一个四则运算表达式的形式为S,那么它一定是一个以等号结尾的运算式,即S->exp=,->是推导符号.
运算式exp又可以继续推导成
exp->exp+term|exp-term|term
exp表示加减运算,term表示乘除运算.这个推导式反映了乘除的优先级比加减高.
即要先计算乘除式的结果,再来加减.
term可以推导如下:
term->term*factor|term/factor|factor
factor->num|(E)
factor是数字或者一个被括号括住的运算式,表示最高优先级.
数字本身是不带运算的,是原子性的,肯定是最高优先级.
括号是被规定了优先计算.
这个程序的代码就是按照上面的推导式,用递归方式来分析运算式的.

‘陆’ 简单计算器的编写

这是个支持表达式的计算器,代码很短。
可以输入类似(3+3*2)*5+6这样的表达式,自己看吧。
不懂其中的原理来找我,或者自助一下,学点编译原理的知识,一定要懂EBNF,EBNF不知道是什么东西?那就google一下吧。
/*
simple integer arithmetic calculator according to the EBNF
<exp> -> <term>{<addop><term>}
<addop>->+|-
<term>-><factor>{<mulop><factor>}
<mulop> -> *
<factor> -> ( <exp> )| Number
Input a line of text from stdin
Outputs "Error" or the result.
*/
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

char token;/*global token variable*/
/*function prototypes for recursive calls*/
int exp(void);
int term(void);
int factor(void);

void error(void)
{
fprintf(stderr,"Error\n");
exit(1);
}

void match(char expectedToken)
{
if(token==expectedToken)token=getchar();
else error();
}

main()
{
int result;
token = getchar();/*load token with first character for lookahead*/
result = exp();
if(token=='\n')/*check for end of line */
printf("Result = %d\n",result);
else error();/*extraneous cahrs on line*/
return 0;
}

int exp(void)
{
int temp = term();
while((token=='+')||(token=='-'))
switch(token)
{
case '+':
match('+');
temp+=term();
break;
case '-':
match('-');
temp-=term();
break;
}
return temp;
}

int term(void)
{
int temp = factor();
while (token=='*')
{
match('*');
temp*=factor();
}
return temp;
}

int factor(void)
{
int temp;
if(token=='('){
match('(');
temp = exp();
match(')');
}
else if(isdigit(token)){
ungetc(token,stdin);
scanf("%d",&temp);
token = getchar();
}
else error();
return temp;
}

‘柒’ 怎么用VB程序做计算器啊

其实比较简单啦,用一个窗体就可以实现啦!
我自己写的,你可以看看
Option Explicit
Dim strNumber As String
Dim strPoint As String
Dim dblNum1 As Double
Dim intOperator As Integer
'清除结果
Private Sub cmdGT_Click()
txtDisplay.Text = "0."
strNumber = ""
strPoint = "."
intOperator = 7
End Sub
'输入数字
Private Sub cmdNumber_Click(Index As Integer)
strNumber = strNumber & cmdNumber(Index).Caption
txtDisplay.Text = strNumber & strPoint
End Sub

Private Sub cmdOnOff_Click()
End
End Sub
'运算过程
Private Sub cmdOperator_Click(Index As Integer)
Dim dblnum2 As Double
'是第一次单击运算符时,将输入的值先赋给第一个数,否则赋值给第二个数进行运算
If intOperator = 7 Then
dblNum1 = CDbl(txtDisplay.Text)
Else
dblnum2 = CDbl(Val(txtDisplay.Text))
'根据输入的符号进行运算
'求普通运算
Select Case intOperator
Case 0
dblNum1 = dblNum1 + dblnum2
Case 1
dblNum1 = dblNum1 - dblnum2
Case 2
dblNum1 = dblNum1 * dblnum2
Case 3
If dblnum2 <> 0 Then
dblNum1 = dblNum1 / dblnum2
Else
MsgBox "除数不能为“0”!请重新输入除数。", vbOKOnly + vbInformation, "除零错误"
Index = intOperator
End If
Case 6
dblNum1 = dblNum1 * dblnum2 / 100
End Select
End If

'取得当前输入的运算符,以做下次运算
intOperator = Index
strNumber = ""
txtDisplay = CStr(dblNum1)
'判断是否为文本框中的数字加点
If Not txtDisplay Like "*.*" Then
txtDisplay.Text = txtDisplay.Text & "."
End If
End Sub

Private Sub cmdOtherOper_Click(Index As Integer)
Dim dblNum As Double
'求平方根,平方,
dblNum = CDbl(Val(txtDisplay.Text))

Select Case Index
Case 0
'验证数据是否有效
If dblNum >= 0 Then
txtDisplay.Text = CStr(Sqr(dblNum))
Else
MsgBox "负数不能开平方根!", _
vbOKOnly + vbCritical, "开平方根错误"
End If
Case 1
txtDisplay.Text = CStr(dblNum ^ 2)
End Select
'判断是否为文本框中的数字加点
If Not txtDisplay Like "*.*" Then
txtDisplay.Text = txtDisplay.Text & "."
End If
End Sub

Private Sub cmdPoint_Click()
strNumber = strNumber & strPoint
strPoint = ""
End Sub

Private Sub Form_KeyDown(KeyCode As Integer, Shift As Integer)
'使被按下的数字键的对应按钮取得焦点
Select Case KeyCode
Case 48 To 57
cmdNumber(KeyCode - 48).SetFocus
Case 96 To 105
cmdNumber(KeyCode - 96).SetFocus
Case Else
'使按下的符号键对应的按钮取得焦点
If KeyCode = 107 Or (Shift = vbShiftMask And KeyCode = 187) Then
cmdOperator(0).SetFocus
cmdOperator_Click (0)
ElseIf KeyCode = 109 Or KeyCode = 189 Then
cmdOperator(1).SetFocus
cmdOperator_Click (1)
ElseIf KeyCode = 106 Or (Shift = vbShiftMask And KeyCode = 56) Then
cmdOperator(2).SetFocus
cmdOperator_Click (2)
ElseIf KeyCode = 111 Or KeyCode = 191 Then
cmdOperator(3).SetFocus
cmdOperator_Click (3)
ElseIf KeyCode = 13 Then
cmdOperator(7).SetFocus
cmdOperator_Click (7)
ElseIf KeyCode = 8 Then
cmdGT.SetFocus
Call cmdGT_Click
End If
End Select
End Sub
Private Sub Form_KeyPress(KeyAscii As Integer)
'将合法的数据输入到文本框
Select Case KeyAscii
Case 48 To 58
'调用数字键点击处理程序
cmdNumber_Click KeyAscii - 48
KeyAscii = 0
Case 46
'调用小数点输入
cmdPoint_Click
KeyAscii = 0
Case 13
'当敲击回车时,不能触发Form的 KeyUp 事件,因此在这里设置文本框的焦点
txtDisplay.SetFocus
Case Else
KeyAscii = 0
End Select
End Sub

Private Sub Form_KeyUp(KeyCode As Integer, Shift As Integer)
txtDisplay.SetFocus
End Sub

Private Sub Form_Load()
strNumber = ""
strPoint = "."
intOperator = 7
End Sub

‘捌’ 怎么用C++设计一个简单的计算机

你说的是设计一个能运算的计算器吧?
下面是代码:

// The desk calulator

// includes character-level input (sec6.1.3) and
// command line input (sec6.1.7),
// but no namespaces and
// no exceptions

// pp 107-119, sec 6.1, A Desk Calculator

// uses += rather than push_back() for string
// to work around standard library bug

// uses istrstream from <strstream> rather than istringstream from <sstream>
// to work around standard library bug

// No guarantees offered. Constructive comments to [email protected]

/*
program:
END // END is end-of-input
expr_list END

expr_list:
expression PRINT // PRINT is semicolon
expression PRINT expr_list

expression:
expression + term
expression - term
term

term:
term / primary
term * primary
primary

primary:
NUMBER
NAME
NAME = expression
- primary
( expression )
*/

#include <string>
#include <cctype>
#include<iostream>
#include<map>

//#include<sstream> // string streams
#include<strstream> // C-style string streams

using namespace std;

istream* input; // pointer to input stream

int no_of_errors; // note: default initialized to 0

double error(const char* s)
{
no_of_errors++;
cerr << "error: " << s << '\n';
return 1;
}

enum Token_value {
NAME, NUMBER, END,
PLUS='+', MINUS='-', MUL='*', DIV='/',
PRINT=';', ASSIGN='=', LP='(', RP=')'
};

Token_value curr_tok = PRINT;
double number_value;
string string_value;

Token_value get_token()
{
char ch;

do { // skip whitespace except '\en'
if(!input->get(ch)) return curr_tok = END;
} while (ch!='\n' && isspace(ch));

switch (ch) {
case ';':
case '\n':
return curr_tok=PRINT;
case '*':
case '/':
case '+':
case '-':
case '(':
case ')':
case '=':
return curr_tok=Token_value(ch);
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
case '.':
input->putback(ch);
*input >> number_value;
return curr_tok=NUMBER;
default: // NAME, NAME=, or error
if (isalpha(ch)) {
string_value = ch;
while (input->get(ch) && isalnum(ch))
string_value += ch; // string_value.push_back(ch);
// to work around library bug
input->putback(ch);
return curr_tok=NAME;
}
error("bad token");
return curr_tok=PRINT;
}
}

map<string,double> table;

double expr(bool); // cannot do without

double prim(bool get) // handle primaries
{
if (get) get_token();

switch (curr_tok) {
case NUMBER: // floating-point constant
{ double v = number_value;
get_token();
return v;
}
case NAME:
{ double& v = table[string_value];
if (get_token() == ASSIGN) v = expr(true);
return v;
}
case MINUS: // unary minus
return -prim(true);
case LP:
{ double e = expr(true);
if (curr_tok != RP) return error(") expected");
get_token(); // eat ')'
return e;
}
default:
return error("primary expected");
}
}

double term(bool get) // multiply and divide
{
double left = prim(get);

for (;;)
switch (curr_tok) {
case MUL:
left *= prim(true);
break;
case DIV:
if (double d = prim(true)) {
left /= d;
break;
}
return error("divide by 0");
default:
return left;
}
}

double expr(bool get) // add and subtract
{
double left = term(get);

for (;;) // ``forever''
switch (curr_tok) {
case PLUS:
left += term(true);
break;
case MINUS:
left -= term(true);
break;
default:
return left;
}
}

int main(int argc, char* argv[])
{

switch (argc) {
case 1: // read from standard input
input = &cin;
break;
case 2: // read argument string
// input = new istringstream(argv[1]);
input = new istrstream(argv[1]);
break;
default:
error("too many arguments");
return 1;
}

table["pi"] = 3.1415926535897932385; // insert predefined names
table["e"] = 2.7182818284590452354;

while (*input) {
get_token();
if (curr_tok == END) break;
if (curr_tok == PRINT) continue;
cout << expr(false) << '\n';
}

if (input != &cin) delete input;
return no_of_errors;d
}

‘玖’ 用c++编写一个简单的计算器

你的这个要求绝对不会有人满足的。因为你的这个要求不只是一个编写一个最简单的计算器问题。
主要是在编写这个程序的过程中,还涉及到了计算机软件专业中的“编译原理”这门课程的其中重要知识。即:表达式的分析与求值(即:何时将相应的数字、以及运算符压入堆栈,何时又需要将相应的数字、以及运算符弹出堆栈)、以及对运算符优先级的处理(例如:括号的最优先最高、乘除法的优先级高于加减法)。
所以说你的这个要求可以说是:至少是一个大作业了。而且了,另外还有一个别的任何人无法满足你的原因就是:对于编写任何程序来说,都是必须要通过自己上机编写程序源代码、编译、链接、通过花费很多的时间和精力去调试,最终才能够得出程序的正确运行结果。

热点内容
ark手游怎么免费创建私人服务器 发布:2025-02-12 12:51:51 浏览:400
linux键盘布局 发布:2025-02-12 12:50:57 浏览:682
linuxlc 发布:2025-02-12 12:42:51 浏览:477
安卓协议一般支持哪个系统比较好 发布:2025-02-12 12:42:47 浏览:511
书脊算法 发布:2025-02-12 12:42:41 浏览:817
xp编程器功能介绍 发布:2025-02-12 12:37:00 浏览:973
海康威视监控密码是多少位 发布:2025-02-12 12:20:29 浏览:584
安卓的自带浏览器在哪里 发布:2025-02-12 12:20:29 浏览:722
望海潮上传 发布:2025-02-12 12:16:08 浏览:672
javathread源码 发布:2025-02-12 12:12:37 浏览:907