위 챗 애플 릿 간이 계산기 실현
소개
1.접미사 표현 식
접두사 표현 식 은 통용 되 는 산술 이나 논리 공식 표시 방법 으로 조작 부 호 는 접두사 형식 으로 조작 수의 중간 에 있다.접미사 표현 식 은 사람들 이 자주 사용 하 는 산술 표현 방법 이다.
사람의 뇌 는 접두사 표현 식 을 이해 하고 분석 하기 쉽 지만 컴퓨터 에 서 는 접두사 표현 식 이 복잡 하기 때문에 표현 식 의 값 을 계산 할 때 접두사 표현 식 을 접두사 나 접두사 표현 식 으로 바 꾼 다음 에 값 을 구 해 야 합 니 다.컴퓨터 에 있어 서 접두사 나 접두사 표현 식 의 값 을 계산 하 는 것 은 매우 간단 하 다.
2.접미사 표현 식
왼쪽 에서 오른쪽으로 표현 식 을 스 캔 하고 숫자 를 만 났 을 때 스 택 에 숫자 를 누 르 고 연산 자 를 만 났 을 때 스 택 꼭대기 의 두 개의 수 를 팝 업 하고 연산 자 를 사용 하여 해당 하 는 계산(차 정 요소 op 스 택 꼭대기 요소)을 하고 결 과 를 스 택 에 넣 습 니 다.표현 식 의 맨 오른쪽 끝 까지 상기 과정 을 반복 하고 마지막 으로 연산 한 값 은 표현 식 의 결과 입 니 다.
예:
(1)8+4-62 접미사 표현 식 으로 다음 과 같이 표시 합 니 다.
8 4+6 2-
(2)2*(3+5)-4+7/1 접미사 표현 식 으로 다음 과 같이 표시 합 니 다.
3 5+2*7 1/4-+
예 를 들 어 접미사 표현 식'34+5'× 6 -”:
(1)왼쪽 에서 오른쪽으로 스 캔 하여 3 과 4 를 스 택 에 넣 습 니 다.
(2)+연산 자 를 만 났 기 때문에 4 와 3(4 는 스 택 정상 요소,3 은 차 정상 요소,접두사 표현 식 과 비교)을 팝 업 하여 3+4 의 값 을 계산 하고 7 을 얻어 7 을 스 택 에 넣 습 니 다.
(3)5 를 창고 에 넣는다.
(4)다음은×연산 자,따라서 5 와 7 을 팝 업 하여 7 을 계산 합 니 다.×5=35,35 를 창고 에 넣는다.
(5)6 을 창고 에 넣는다.
(6)마지막 은-연산 자로 35-6 의 값,즉 29 를 계산 하여 최종 결 과 를 얻는다.
프로그램 코드
1.코드
app.js 설정 코드 는 다음 과 같 습 니 다.
// app.js
App({
onLaunch() {
//
const logs = wx.getStorageSync('logs') || []
logs.unshift(Date.now())
wx.setStorageSync('logs', logs)
//
wx.login({
success: res => {
// res.code openId, sessionKey, unionId
}
})
},
globalData: {
userInfo: null
},
calculator:{
express:'', //
strList:[], // ( )
strListP:[], // ( )
list:[], // ( )
calculate:[] // ( )
}
})
2.논리 코드calculator.js 코드 는 다음 과 같 습 니 다.
// pages/calculator/calculator.js
const app = getApp()
Page({
/**
*
*/
data: {
operators: ['AC', 'DEL', '%', '/', '7', '8', '9', '×', '4', '5', '6', '+', '1', '2', '3', '-', '0', '.'],
res: '=',
expression: '0',
},
clearAll() {
this.setData({
expression: '0',
result: ''
})
},
click: function (event) {
const val = event.target.dataset.value;
if (val == 'AC') {
this.clearAll();
} else if (val == 'DEL') {
if (this.data.expression != '0') {
const res = this.data.expression.substr(0, this.data.expression.length - 1);
this.setData({
expression: res
})
}
} else {
var len = this.data.expression.length;
var s = this.data.expression.substring(len - 1, len);
if ((this.checkOperator(s)) && this.checkOperator(val)) {
const res = this.data.expression.substr(0, this.data.expression.length);
this.setData({
expression: res
})
} else {
if ((this.data.expression == '0') && (val == '.')) {
this.setData({
expression: this.data.expression + String(val)
})
} else {
this.setData({
expression: this.data.expression === '0' ? val : this.data.expression + String(val)
})
}
}
}
},
result() {
app.calculator.strList.length = 0;
app.calculator.strListP.length = 0;
app.calculator.list.length = 0;
app.calculator.calculate.length = 0;
this.expressToStrList(this.data.expression);
let tempList = app.calculator.strList;
this.expressToStrListP(tempList);
let tempP = app.calculator.strListP
for (let m in tempP) {
if (this.checkOperator(tempP[m])) {
let op1 = app.calculator.calculate[0];
app.calculator.calculate.shift();
let op2 = app.calculator.calculate[0];
app.calculator.calculate.shift();
app.calculator.calculate.unshift(this.countDetail(op2, tempP[m], op1));
} else {
app.calculator.calculate.unshift(tempP[m])
}
}
this.setData({
result: app.calculator.calculate[0]
});
},
countDetail(num1, operator, num2) {
let result = 0.0;
try {
if (operator == "×") {
result = parseFloat(num1) * parseFloat(num2);
} else if (operator == "/") {
result = parseFloat(num1) / parseFloat(num2);
} else if (operator == "%") {
result = parseFloat(num1) % parseFloat(num2);
} else if (operator == "+") {
result = parseFloat(num1) + parseFloat(num2);
} else {
result = parseFloat(num1) - parseFloat(num2);
}
} catch (error) {
}
return result;
},
expressToStrListP(tempList) {//
for (let item in tempList) {
if (this.checkOperator(tempList[item])) {
if (app.calculator.list.length == 0) {
app.calculator.list.unshift(tempList[item]);
} else {
if (this.compaerOperator(app.calculator.list[0], tempList[item])) {
for (let x in app.calculator.list) {
app.calculator.strListP.push(app.calculator.list[x]);
}
app.calculator.list.length = 0;
app.calculator.list.unshift(tempList[item]);
} else {
app.calculator.list.unshift(tempList[item]);
}
}
} else {
app.calculator.strListP.push(tempList[item]);
}
}
if (app.calculator.list.length > 0) {
for (let x in app.calculator.list) {
app.calculator.strListP.push(app.calculator.list[x]);
}
app.calculator.list.length = 0;
}
},
compaerOperator(op1, op2) {
if ((op1 == "%" || op1 == "×" || op1 == "/") && (op2 == "-" || op2 == "+")) {
return true;
} else {
return false;
}
},
expressToStrList(expression) { //
let temp = '';
for (let i = 0; i < expression.length; i++) {
if (i == 0 && expression[i] == "-") {
temp = temp + expression[i];
} else {
if (this.checkDigit(expression[i])) {
temp = temp + expression[i];
} else {
if (temp.length > 0) {
if (expression[i] == ".") {
temp = temp + expression[i];
} else {
app.calculator.strList.push(parseFloat(temp));
temp = '';
app.calculator.strList.push(expression[i]);
}
} else {
temp = temp + expression[i];
}
}
}
}
if (temp.length > 0 && this.checkDigit(temp.substring(temp.length - 1))) {
app.calculator.strList.push(parseFloat(temp));
temp = '';
}
},
//
checkOperator(input) {
if (input == "-" || input == "+" || input == "/" || input == "%" || input == "×") {
return true;
} else {
return false;
}
},
//
checkDigit(input) {
if ((/^[0-9]*$/.test(input))) {
return true;
} else {
return false;
}
},
})
3.인터페이스 코드calculator.js 코드 는 다음 과 같 습 니 다.
<!--pages/calculator/calculator.wxml-->
<view class="contaniner">
<view class="displayer">
<view class="text">{{expression}}</view>
<view class="result">={{result}}</view>
</view>
<view class="btnArea">
<block wx:for="{{operators}}">
<view class="btn" data-value="{{item}}" capture-bind:tap="click">{{item}}</view>
</block>
<view class="btn btn1" data-value="{{res}}" bindtap="result">{{res}}</view>
</view>
</view>
4.스타일 코드calculator.js 코드 는 다음 과 같 습 니 다.
/* pages/calculator/calculator.wxss */
.container1{
width: 100%;
height: 100%;
}
.displayer{
border: 1px solid #f1f3f3;
width: 100%;
height: 602![ ](https://img-blog.csdnimg.cn/20210328162054440.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQzNDI4MjE5,size_16,color_FFFFFF,t_70#pic_center)
rpx;
font-size: 45rpx;
background-color: rgba(241, 243, 243, 1.0);
}
.btnArea{
display: flex;
flex-flow: row wrap;
justify-content: flex-start;
padding: 3rpx;
margin: 0;
background-color: rgb(241, 243, 243);
}
.btn{
width: 185rpx;
display: flex;
align-items: center;
height: 120rpx;
justify-content: center;
border: 1rpx solid #e8eaeb;
color: black;
background-color: #F7F8F9;
}
.btn1{
width: 370rpx;
}
.text{
width: 100%;
height: 10%;
text-align: right;
margin-top: 470rpx;
background-color: rgba(241, 243, 243, 1.0);
position: absolute;
word-break: break-word;
}
.result{
width: 100%;
height: 58rpx;
text-align: right;
margin-top: 530rpx;
background-color: rgba(241, 243, 243, 1.0);
position: absolute;
word-break: break-word;
}
프로그램 캡 처총화
스 택 을 배열 로 만 든 다음 표현 식 을 접미사 표현 식 으로 바 꾸 고 접미사 표현 식 으로 바 꾸 어 스 택 을 이용 하여 계산 합 니 다.
이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
6일차_파이썬으로 계산기 만들어버리기유튜브를 보면서 만든 초초초 간단 계산기 두두등장! 기왕 만드는거 '남들과는 다른 비주얼로 해보자!' 컨셉을 잡았다 그럼 그 색상은? 심지어 다른 색상명에도 구분이 가지 않는 것들도 보였다... 그래서 간단히(?) ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.