用wpf简单写一个计算器

这里只会展示成果,记录一下我实现的过程。

用wpf做界面,不用多说,将各个按钮对应数字或者运算符,点击‘=’号的时候将字符串放入写好的算法中得出结果。

当然,算法也是我自己写的,不能显示错误表达式,在一些小范围数据还是可以接受的,只是突发奇想想写这个,但是算法没有经过测试,正确率有待提高。

这里展示一下无括号的 ‘加减乘除’ 计算方法

思路很简单,数字和符号分开储存,然后计算局部结果最后存入栈中,最后取出栈中元素全部相加。

当然如果有括号的,直接使用递归或者栈计算局部结果,最后也是将结果放入栈中求和。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace Calculator.Algorithm
{
    public class NoParentheses
    {
        public string? str { get; set; }

        private Stack<decimal> st = new Stack<decimal>();
        private string[] sArry;
        private List<char> list;
        public NoParentheses()
        {
            sArry = new string[] { };
            list = new List<char>();
        }
        public decimal Compute(string str)
        {
            this.str = str;
            list.Clear();
            sArry = str.Split(new char[] { '+', '*', '/', '-' }, StringSplitOptions.RemoveEmptyEntries);
            /*
             * list储存符号,sArry储存数字
             * 因为输入的第一个是正数无符号的,所以判断一下是否第一个数要‘+’号
             */
            if (str[0] != '-')
            {
                list.Add('+');
            }
            foreach (char s in str)
            {
                if (s == '-' || s == '*' | s == '/' || s == '+')
                {
                    list.Add(s);
                }
            }
            //Console.WriteLine($"{list.Count}+{sArry.Length}");
            /*
             * 开始运算,将所有运算结果储存到栈里
             * 最后直接相加
             */
            for (int i = 0; i < list.Count; i++)
            {
                if (list[i] == '+')
                {
                    st.Push(decimal.Parse(sArry[i]));
                }
                else if (list[i] == '-')
                {
                    st.Push(-decimal.Parse(sArry[i]));
                }
                else if (list[i] == '*')
                {
                    decimal p = st.Pop();
                    p *= decimal.Parse(sArry[i]);
                    st.Push(p);
                }
                else
                {
                    decimal p = st.Pop();
                    p /= decimal.Parse(sArry[i]);
                    st.Push(p);
                }
            }
            decimal res = 0;
            //最后结果相加
            while (st.Count != 0)
            {
                res += st.Pop();
            }
            
            return res;
        }
    }
}

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值