android 小玩意儿 关于科学计算器,多则多项多级计算的算法实现

本文主要是介绍android 小玩意儿 关于科学计算器,多则多项多级计算的算法实现,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

近日学习了android的基本界面和调用,试试写一个科学计算器。虽然还没找到工作,可是貌似工作可遇而不可求啊! 开心就好...


需求:

1.计算器显示输入的表达式

2.支持()运算符

3.支持多次方、三角函数(cos,tan,sin)

4.支持10位π、e

5.支持快速开方

6.支持逻辑运算

7.运算精度和范围(10^-8 - 10^8)

8.支持all_clear快速清理表达式阅览框和结果框,支持del删除表达式最后一个字符


分析:

该计算器的重点不在于如何计算,在于如何把表达式导入计算机交给系统计算。如:输入表达式1+1*2 ,需要对表达式进行分析和求解。

设计解决方案:

   1.使用二叉树的形式用结点存储值  ,按优先级进行中序排序 ,根结点即为最终结果

   2.直接使用数组的形式,对下标进行计算


最终解决方案:


界面设计:




-------算法一 直接使用数组实现(不完整)--------------------------------------------------------------------------------------------------------------------------------------------------------


//分析表达式
/*
* 以+、-、*、/为分割符号 将所有数字取出来 存入数组
* 将所有符号取出来  存入数组
* 遍历符号数组,设置优先级  *、/优先级为1; +,-优先级为0

* 按优先级和数组下标为次序进行计算
*/
private double calculate(StringBuffer expressionStr){
double result=0;
List symbol = new ArrayList();
List<StringBuffer> nums = new ArrayList();


char temp;
boolean flag=false;//判断连续数字
   for(int i=0,index_nums=-1;i<expressionStr.length();i++){
    temp=expressionStr.charAt(i);
    if('+'==temp||'-'==temp||'X'==temp||'/'==temp){
    symbol.add(temp);
    flag=false;
    }else{//('0'==temp||'1'==temp||'2'==temp||'3'==temp||'4'==temp||'5'==temp||'6'==temp||'7'==temp||'8'==temp||'9'==temp||'.'==temp){
   
    if(flag==true){
    nums.get(index_nums).append(temp);
    }else {
    index_nums++;
    nums.add(new StringBuffer(temp+""));
    }
    flag=true;
    }
   }


   
   //将组合的数字字符串每一个转型为double型
   List<Double> nums_dou=new ArrayList();
   for(int i=0;i<nums.size();i++){
    nums_dou.add(Double.valueOf(nums.get(i).toString()));
   }
   
   //开始计算
   //计算方法,采用数组的形式
   List<Double> results = new ArrayList();
   for(int i=0;i<symbol.size();i++){
    results.add(0d);
   }
   for(int i=0;i<symbol.size();i++){
    if(i==0){
    if(symbol.get(i).toString().equals("X")){
    results.set(i, nums_dou.get(i)*nums_dou.get(i+1));
    }
    if(symbol.get(i).toString().equals("/")){
    results.set(i, nums_dou.get(i)/nums_dou.get(i+1));
    }
    if(symbol.get(i).toString().equals("+")){
    results.set(i, Double.valueOf((nums_dou.get(i)+nums_dou.get(i+1))));
    }
    if(symbol.get(i).toString().equals("-")){
    results.set(i, nums_dou.get(i)-nums_dou.get(i+1));
    }
    }else
    if(symbol.get(i).toString().equals("X")||symbol.get(i).toString().equals("/")){
    if(results.get(i-1)==0){
    if(symbol.get(i).toString().equals("X")){
    results.set(i, nums_dou.get(i)*nums_dou.get(i+1));
    }else{
    results.set(i, nums_dou.get(i)/nums_dou.get(i+1));
    }
    }else {
    if(symbol.get(i).toString().equals("X")){
    results.set(i, results.get(i-1)*nums_dou.get(i+1));
    }else{
    results.set(i, results.get(i-1)/nums_dou.get(i+1));
    }
    }
    }else {
    if(results.get(i-1)==0){
    if(symbol.get(i).toString().equals("+")){
    results.set(i, nums_dou.get(i)+nums_dou.get(i+1));
    }else{
    results.set(i, nums_dou.get(i)-nums_dou.get(i+1));
    }
    }else {
    if(symbol.get(i).toString().equals("+")){
    results.set(i, results.get(i-1)+nums_dou.get(i+1));
    }else{
    results.set(i, results.get(i-1)-nums_dou.get(i+1));
    }
    }
    }
    System.out.println("results.get(i)->>"+results.get(i));
    result=results.get(i);
   }
   
   System.out.println("Result->>"+result);
return result;
}




--------------------------我想还是用栈或者二叉树比较好实现点----------


因为java中没有栈这种数据结构,那么只能模拟了。这里我使用数组来模拟栈


package tk.orangers.calculate;


//利用数组实现简单的堆栈
public class arrayStact {
private int pointcounter;// 栈指针
double[] stact = new double[100];


public arrayStact() {
for (int i = 0; i < stact.length; i++)
stact[i] = -1;
pointcounter = 0;
}


public void push(double temp) {
pointcounter++;


if (pointcounter < 100) {
for (int i = pointcounter; i > 0; i--)
stact[i] = stact[i - 1];
stact[0] = temp;


} else
System.out
.println("Error:表达式长度超过了栈大小~!\n");
}


public double pop() {
double temptop = -1;
if (isEmpty()) {
System.out.println("Error:栈是空的!\n");
} else {
temptop = stact[0];
for (int i = 0; i < pointcounter; i++)
stact[i] = stact[i + 1];


pointcounter--;
}
return temptop;
}


public double gettop() {
return stact[0];
}


private boolean isEmpty() {
if (pointcounter == 0)
return true;
else
return false;
}
}



分析字符串表达式,将字符串中的数字与符号分割开来

之后分别使用两个栈来存放运算符号和运算者

关于优先级,借鉴了数据结构中的验证矩阵来求解

根据符号优先级,依据符号栈进行计算



package tk.orangers.calculate;


public class stringAnalysis{
arrayStact stact_nums = new arrayStact();// 存放操作数
arrayStact stact_symbol = new arrayStact();// 存放运算符号
String[] unit = new String[200]; // 存放解析出来的操作数与运算符
int[][] priority = { // + - * / ( ) 优先级比较矩阵
{ 2, 2, 1, 1, 1, 2, 2 }, 
{ 2, 2, 1, 1, 1, 2, 2 }, 
{ 2, 2, 2, 2, 1, 2, 2 },
{ 2, 2, 2, 2, 1, 2, 2 }, 
{ 1, 1, 1, 1, 1, 0, 3 },
{ 2, 2, 2, 2, 3, 2, 2 }, 
{ 1, 1, 1, 1, 1, 3, 0 },
};
// 0表示相等 1表示小于 2表示大于 3表示错误
// + 用0表示,- 用1表示,* 用2表示,/ 用3表示,
// ( 用4表示,) 用5表示,# 用6表示
//横与纵的关系 如:第一行第三列为1 表示+的优先级小于*
private String temp;// 用于构造函数
private int arraypoint = 0;// 记录unit数组的存储长度


private int i = 0;// 读取unit数组的元素


private String tempstring;// 保存临时unit的值


private int start = 0; // 数字字符串开始位置


private int counter = 0; // 字符个数计数


private int target = 0; // 保存开始计数位置


private int lab = 1; // 表示计数结束输出数串


private int index = 0; // 表示字符串读取位置的计数


private int iscorrect = 1;// 表示是否继续读取整个字符串到存放数组(表示是是否是正确地表达式),1表示继续,0表示停止


private int isrecord = 0;// 表示是否存入数组,1表示存入数组合,0表示不存入数组


private int isnext = 1; // 表示检测每一个数组单元值,如果非法为0,不非法为1(即进行下一步)


private int leftbracket = 0, rightbracket = 0;// 左,右括号记数目

private double result=0d;//结果

   public double getResult( ){//计
  return this.result;
   }
public stringAnalysis(String passtemp) {
this.temp = passtemp;
processwhitespace();
processexpression();


if (leftbracket != rightbracket) {
isnext = 0;
System.out
.println("Erro:括号不对称哦~~!");
}


if (isnext == 1)
computeexpression();
}


private void processwhitespace() {//将表达式剔除空格 
String emptystring = "";
String[] tempstring = temp.split(" ");
for (int i = 0; i < tempstring.length; i++) {
emptystring += tempstring[i];
}


System.out.println("Log:被计算的表达式是:\n" + emptystring);
System.out.println("\n");


temp = emptystring + "#";
stact_symbol.push(6);// 初始化操作符堆栈
}


private void partprocessexpression(String tempstringtemp) {
if (iserrorexpression(tempstringtemp))
isnext = 0;
else {
if (tempstringtemp == "-" && index == 0)
isrecord = 1;
else if (temp.charAt(index - 1) == ')') {
unit[arraypoint] = tempstringtemp;
arraypoint++;
} else {
lab = 1;
if (lab == 1) {
target = 0;
lab = 0;


if (counter == 0)
;// ()时候移位
else {
if (isrecord == 1) {
unit[arraypoint] = "-"
+ temp.substring(start, start + counter);// 开始第一位为负数
arraypoint++;
isrecord = 0;
} else {
unit[arraypoint] = ""
+ temp.substring(start, start + counter);
arraypoint++;
}
}
counter = 0;
}


unit[arraypoint] = tempstringtemp;
arraypoint++;
}// end inner else
}// end outer else
}


private void processexpression()// 读取表达式,将预算符号与操作数分开,并存入数组
{
for (; index < temp.length(); index++) {
switch (temp.charAt(index)) {
case '(':
if (iserrorexpression("("))
isnext = 0;
else {
leftbracket++;
unit[arraypoint] = "(";
arraypoint++;
if (temp.charAt(index + 1) == '-'&& temp.charAt(index + 2) - '0' >= 1&& temp.charAt(index + 2) - '0' <= 9) {
int end = 0;
for (int tempm = index + 1; tempm < temp.length(); tempm++) {
if (temp.charAt(tempm) == ')') {
end = tempm;
break;
}
}
unit[arraypoint] = temp.substring(index + 1, end);
arraypoint++;
index = end - 1;
target = 0;
lab = 0;
counter = 0;
}
}// end else
break;
case ')':
if (index == 0)
isnext = 0;
else {
partprocessexpression(")");
rightbracket++;
}
break;
case '+':
if (index == 0)
isnext = 0;
else
partprocessexpression("+");
break;
case '-':
partprocessexpression("-");
break;
case '*':
if (index == 0)
isnext = 0;
else
partprocessexpression("*");
break;
case '/':
if (index == 0)
isnext = 0;
else
partprocessexpression("/");
break;
case '#':
unit[arraypoint] = "#";
break;
default:
if (target == 0) {
start = index;
lab = 0;
target = 1;
}
if (lab == 0)
counter++;
if (start + counter == temp.length() - 1) {
unit[arraypoint] = ""+ temp.substring(start, start + counter);
arraypoint++;


}
}// end switch
}// edn for
}// end processexpression


private boolean iserrorexpression(String errortempstring) {//检查表达式错误
boolean iserror = false;


switch (errortempstring.charAt(0)) {
case '(':
if (temp.charAt(index - 1) == ')'
|| temp.charAt(index + 1) == ')'
|| (temp.charAt(index - 1) >= '0' && temp.charAt(index - 1) <= '9'))


iserror = true;
break;
case ')':
if (temp.charAt(index - 1) == '('
|| temp.charAt(index + 1) == '('
|| (temp.charAt(index + 1) >= '0' && temp.charAt(index + 1) <= '9'))


iserror = true;
break;
case '+':
case '*':
case '/':
if (temp.charAt(index - 1) == '(' || temp.charAt(index - 1) == '+'
|| temp.charAt(index - 1) == '-'
|| temp.charAt(index - 1) == '*'
|| temp.charAt(index - 1) == '/'
|| temp.charAt(index + 1) == ')'
|| temp.charAt(index + 1) == '+'
|| temp.charAt(index + 1) == '-'
|| temp.charAt(index + 1) == '*'
|| temp.charAt(index + 1) == '/')//符号重复性检查


iserror = true;
break;
case '-':
if (index != 0) {
if (temp.charAt(index - 1) == '+'
|| temp.charAt(index - 1) == '-'
|| temp.charAt(index - 1) == '*'
|| temp.charAt(index - 1) == '/'
|| temp.charAt(index + 1) == ')'
|| temp.charAt(index + 1) == '+'
|| temp.charAt(index + 1) == '-'
|| temp.charAt(index + 1) == '*'
|| temp.charAt(index + 1) == '/'){//针对-号的处理  考虑负数情况


iserror = true;
}
if (temp.charAt(index - 1) == '(') {
if (temp.charAt(index + 1) - '0' >= 1
&& temp.charAt(index + 1) - '0' <= 9)
iserror = false;
else


iserror = true;


}
} else {
if (temp.charAt(index + 1) == ')'
|| temp.charAt(index + 1) == '+'
|| temp.charAt(index + 1) == '-'
|| temp.charAt(index + 1) == '*'
|| temp.charAt(index + 1) == '/')


iserror = true;
}
break;
default:
System.out.println("Error6 at" + (index - 1) + "~~" + (index + 1));


}// end switch


return iserror;
}


private void computeexpression() {//计算
tempstring = unit[i];


while (tempstring != "#" || stact_symbol.gettop() != 6) {//遍历unit
if (tempstring != "+" && tempstring != "-" && tempstring != "*"&& tempstring != "/" && tempstring != "("&& tempstring != ")" && tempstring != "#") {
stact_nums.push(Double.parseDouble(unit[i]));//数字入栈
tempstring = unit[++i];
} else {
switch (tempstring.charAt(0)) {//符号入栈 并根据符号优先级进行计算
case '+':
compareandprocess(0);
break;
case '-':
compareandprocess(1);
break;
case '*':
compareandprocess(2);
break;
case '/':
compareandprocess(3);
break;
case '(':
compareandprocess(4);
break;
case ')':
compareandprocess(5);
break;
case '#':
compareandprocess(6);
break;
}// end switch
} // end else
}// end while
}


private void compareandprocess(int a) {
switch (priority[(int)stact_symbol.gettop()][a]) {//优先级验证
case 0:  //优先级相等
stact_symbol.pop();
tempstring = unit[++i];
break;
case 1://优先级小于
stact_symbol.push(a);
tempstring = unit[++i];
break;
case 2://优先级大于当前栈顶符号  则计算
partcompareandprocess();
break;
case 3: {//错误 不可比较的错误
System.out.println("error~!");
System.out.println(stact_symbol.gettop() + "  " + a);
}
}
}


private void partcompareandprocess() {
double tempa, tempb, tempc;
int tempoperator;
tempoperator = (int)stact_symbol.pop();
tempb = stact_nums.pop();
tempa = stact_nums.pop();


switch (tempoperator) {
case 0:
tempc = tempa + tempb;
stact_nums.push(tempc);
result=tempc;
break;
case 1:
tempc = tempa - tempb;
stact_nums.push(tempc);
result=tempc;
break;
case 2:
tempc = tempa * tempb;
stact_nums.push(tempc);
result=tempc;
break;
case 3:
tempc = tempa / tempb;
stact_nums.push(tempc);
result=tempc;
break;
}
}
}



待续...

这篇关于android 小玩意儿 关于科学计算器,多则多项多级计算的算法实现的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/475120

相关文章

QT Creator配置Kit的实现示例

《QTCreator配置Kit的实现示例》本文主要介绍了使用Qt5.12.12与VS2022时,因MSVC编译器版本不匹配及WindowsSDK缺失导致配置错误的问题解决,感兴趣的可以了解一下... 目录0、背景:qt5.12.12+vs2022一、症状:二、原因:(可以跳过,直奔后面的解决方法)三、解决方

MySQL中On duplicate key update的实现示例

《MySQL中Onduplicatekeyupdate的实现示例》ONDUPLICATEKEYUPDATE是一种MySQL的语法,它在插入新数据时,如果遇到唯一键冲突,则会执行更新操作,而不是抛... 目录1/ ON DUPLICATE KEY UPDATE的简介2/ ON DUPLICATE KEY UP

Python中Json和其他类型相互转换的实现示例

《Python中Json和其他类型相互转换的实现示例》本文介绍了在Python中使用json模块实现json数据与dict、object之间的高效转换,包括loads(),load(),dumps()... 项目中经常会用到json格式转为object对象、dict字典格式等。在此做个记录,方便后续用到该方

JWT + 拦截器实现无状态登录系统

《JWT+拦截器实现无状态登录系统》JWT(JSONWebToken)提供了一种无状态的解决方案:用户登录后,服务器返回一个Token,后续请求携带该Token即可完成身份验证,无需服务器存储会话... 目录✅ 引言 一、JWT 是什么? 二、技术选型 三、项目结构 四、核心代码实现4.1 添加依赖(pom

SpringBoot路径映射配置的实现步骤

《SpringBoot路径映射配置的实现步骤》本文介绍了如何在SpringBoot项目中配置路径映射,使得除static目录外的资源可被访问,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一... 目录SpringBoot路径映射补:springboot 配置虚拟路径映射 @RequestMapp

Python与MySQL实现数据库实时同步的详细步骤

《Python与MySQL实现数据库实时同步的详细步骤》在日常开发中,数据同步是一项常见的需求,本篇文章将使用Python和MySQL来实现数据库实时同步,我们将围绕数据变更捕获、数据处理和数据写入这... 目录前言摘要概述:数据同步方案1. 基本思路2. mysql Binlog 简介实现步骤与代码示例1

Redis实现高效内存管理的示例代码

《Redis实现高效内存管理的示例代码》Redis内存管理是其核心功能之一,为了高效地利用内存,Redis采用了多种技术和策略,如优化的数据结构、内存分配策略、内存回收、数据压缩等,下面就来详细的介绍... 目录1. 内存分配策略jemalloc 的使用2. 数据压缩和编码ziplist示例代码3. 优化的

基于C#实现PDF转图片的详细教程

《基于C#实现PDF转图片的详细教程》在数字化办公场景中,PDF文件的可视化处理需求日益增长,本文将围绕Spire.PDFfor.NET这一工具,详解如何通过C#将PDF转换为JPG、PNG等主流图片... 目录引言一、组件部署二、快速入门:PDF 转图片的核心 C# 代码三、分辨率设置 - 清晰度的决定因

Java Kafka消费者实现过程

《JavaKafka消费者实现过程》Kafka消费者通过KafkaConsumer类实现,核心机制包括偏移量管理、消费者组协调、批量拉取消息及多线程处理,手动提交offset确保数据可靠性,自动提交... 目录基础KafkaConsumer类分析关键代码与核心算法2.1 订阅与分区分配2.2 拉取消息2.3

SpringBoot集成XXL-JOB实现任务管理全流程

《SpringBoot集成XXL-JOB实现任务管理全流程》XXL-JOB是一款轻量级分布式任务调度平台,功能丰富、界面简洁、易于扩展,本文介绍如何通过SpringBoot项目,使用RestTempl... 目录一、前言二、项目结构简述三、Maven 依赖四、Controller 代码详解五、Service