examples: vfmt calculator.v

pull/6199/head
Charadon 2020-08-23 14:18:37 +00:00 committed by GitHub
parent 1c9e02094c
commit bb60b4227e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 135 additions and 134 deletions

View File

@ -1,6 +1,5 @@
// Q: What's this?
// A: This is a mini "home-made" calculator. You may also regard it as a very elementary version of "interpreter".
import os
const (
@ -23,8 +22,7 @@ fn expr_to_rev_pol(expr string) ?[]string {
if end_pos > pos {
stack << expr[pos..end_pos]
pos = end_pos
}
else if end_pos==pos {
} else if end_pos == pos {
op := expr[pos].str()
match op {
'(' {
@ -52,7 +50,7 @@ fn expr_to_rev_pol(expr string) ?[]string {
stack.delete(stack.len - 1)
}
else {
return error('err: invalid character `${op}`')
return error('err: invalid character `$op`')
}
}
pos++
@ -72,17 +70,22 @@ fn eval_rev_pol(rev_pol []string) ?f64 {
for item in rev_pol {
if is_num_string(item) {
stack << item.f64()
}
else {
} else {
if stack.len >= 2 {
oprand_r := stack.last()
stack.delete(stack.len - 1)
oprand_l := stack.last()
stack.delete(stack.len - 1)
match item {
'+' { stack << oprand_l+oprand_r }
'-' { stack << oprand_l-oprand_r }
'*' { stack << oprand_l*oprand_r }
'+' {
stack << oprand_l + oprand_r
}
'-' {
stack << oprand_l - oprand_r
}
'*' {
stack << oprand_l * oprand_r
}
'/' {
if oprand_r == 0 {
return error('err: divide by zero')
@ -91,8 +94,7 @@ fn eval_rev_pol(rev_pol []string) ?f64 {
}
else {}
}
}
else {
} else {
return error('err: invalid expression')
}
}
@ -109,10 +111,9 @@ fn is_num_string(str string) bool {
return true
}
fn main() {
println('Please enter the expression you want to calculate, e.g. 1e2+(3-2.5)*6/1.5 .')
println('Enter \'exit\' or \'EXIT\' to quit.')
println("Enter \'exit\' or \'EXIT\' to quit.")
mut expr_count := 0
for {
expr_count++