C#,茅塞顿开的代码——最少的程序实现通用型科学计算器

本文主要是介绍C#,茅塞顿开的代码——最少的程序实现通用型科学计算器,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

计算器是经常遇到的编程作业。

一般都是实现加、减、乘、除四则运算的普通计算器。

这里介绍用几十行C#代码实现的复杂的《科学计算器》,可以计算各种函数。

不知道其他语言实现同样的功能需要编写多少行代码?20000行?

using System;
using System.Text;
using System.Drawing;
using System.Collections.Generic;
using System.Windows.Forms;
using System.CodeDom.Compiler;
using Microsoft.CSharp;
using System.Reflection;
 
namespace HyperCalculator
{
    public partial class Form1 : Form
    {
        // 预定义各 按键 的文字
        string[] operationArray = new string[] {
            "Abs",  "Acos", "(",    ",",    ")",    "Backspace",   "C",
            "Asin", "Atan", "7",    "8",    "9",    "/",    "=",
            "Atan2",    "Ceiling",  "4",    "5",    "6",    "*",    "",
            "Cos",  "Cosh", "1",    "2",    "3", "-",    "",
            "E",    "Exp",  "0",    "", ".",    "+",    "",
            "Floor",    "Log",  "Log10",    "Max",  "Min",   "PI",   "Pow",
            "Sign", "Sin",  "Sinh", "Sqrt", "Tan",  "Tanh", "",
        };
        List<Button> buttonList = new List<Button>();
        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            // 动态加载液晶LED字体(请下载压缩包,内含)
            System.Drawing.Text.PrivateFontCollection privateFonts = new System.Drawing.Text.PrivateFontCollection();
            privateFonts.AddFontFile("LEDCalculatorBold.ttf");
            System.Drawing.Font font = new Font(privateFonts.Families[0], 21);
            textBox1.Font = font;
            textBox1.Text = "0";
            textBox1.TextAlign = HorizontalAlignment.Right;
            // 打包按键集合
            Control.ControlCollection sonControls = this.Controls;
            foreach (Control control in sonControls)
            {
                if (control.GetType() == typeof(Button))
                {
                    buttonList.Add((Button)control);
                }
            }
            // 按位置排序,以及匹配实现预定义的文字
            buttonList.Sort(delegate (Button a, Button b)
            {
                return Comparer<int>.Default.Compare(a.Left + a.Top * button1.Height, b.Left + b.Top * button1.Height);
            });
            Font nf = new Font(Font.FontFamily, 21);
            for (int i = 0; i < buttonList.Count && i < operationArray.Length; i++)
            {
                buttonList[i].Cursor = Cursors.Hand;
                buttonList[i].Text = operationArray[i];
                if (buttonList[i].Text.Length == 1 && operationArray[i] != "E")
                {
                    buttonList[i].Font = nf;
                    buttonList[i].BackColor = Color.FromArgb(225, 255, 200);
                }
                if (operationArray[i].Trim().Length > 0) buttonList[i].Click += button_Click;
            }
        }
 
        private void button_Click(object sender, EventArgs e)
        {
            Button btn = (Button)sender;
            if (btn.Text == "=")
            {
                // 等号就是计算啦!任何计算,都是执行一个表达式而已!
                CSharpCodeProvider objCSharpCodePrivoder = new CSharpCodeProvider();
                ICodeCompiler objICodeCompiler = objCSharpCodePrivoder.CreateCompiler();
                CompilerParameters objCompilerParameters = new CompilerParameters();
                objCompilerParameters.ReferencedAssemblies.Add("System.dll");
                objCompilerParameters.GenerateExecutable = false;
                objCompilerParameters.GenerateInMemory = true;
                // 编译 Code() 返回的含有计算表达式的完整的 C# 程序;
                CompilerResults cr = objICodeCompiler.CompileAssemblyFromSource(objCompilerParameters, Code());
                if (cr.Errors.HasErrors)
                {
                    StringBuilder sb = new StringBuilder();
                    foreach (CompilerError err in cr.Errors)
                    {
                        sb.AppendLine(err.ErrorText);
                    }
                    MessageBox.Show(sb.ToString(), "表达式错误");
                }
                else
                {
                    // 执行 C# 程序的指定 函数,并得到返回值,就是计算结果;
                    Assembly objAssembly = cr.CompiledAssembly;
                    object objHelloWorld = objAssembly.CreateInstance("Beijing.Legalsoft.Ltd.HyperCalculator");
                    MethodInfo objMI = objHelloWorld.GetType().GetMethod("Run");
                    double resultValue = (double)objMI.Invoke(objHelloWorld, null);
                    textBox1.Text = resultValue + "";
                }
                return;
            }
            if (btn.Text == "C")
            {
                textBox1.Text = "0";
                return;
            }
            if (btn.Text == "Backspace")
            {
                if (textBox1.Text.Length > 1)
                {
                    textBox1.Text = textBox1.Text.Substring(0, textBox1.Text.Length - 1);
                }
                else
                {
                    textBox1.Text = "0";
                }
                return;
            }
            if (textBox1.Text == "0") textBox1.Text = "";
            if (textBox1.Text.Length + btn.Text.Length < 45)
            {
                textBox1.Text += btn.Text;
            }
        }
        private string Code()
        {
            // 按输入的文字构造一个完整的 C# 程序;包括命名空间,类与方法(函数)
            string state = textBox1.Text;
            foreach (string ps in operationArray)
            {
                if (ps.Trim().Length > 1 || ps == "E")
                {
                    state = state.Replace(ps, "Math." + ps);
                }
            }
            state = state.Replace("Math.Math.", "Math.");
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("using System;");
            sb.AppendLine("namespace Beijing.Legalsoft.Ltd");
            sb.AppendLine("{");
            sb.AppendLine("    public class HyperCalculator");
            sb.AppendLine("    {");
            sb.AppendLine("        public double Run()");
            sb.AppendLine("        {");
            sb.AppendLine("            return (" + state + ");");
            sb.AppendLine("        }");
            sb.AppendLine("    }");
            sb.AppendLine("}");
            return sb.ToString();
        }
    }
}

这篇关于C#,茅塞顿开的代码——最少的程序实现通用型科学计算器的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



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

相关文章

C#使用Spire.Doc for .NET实现HTML转Word的高效方案

《C#使用Spire.Docfor.NET实现HTML转Word的高效方案》在Web开发中,HTML内容的生成与处理是高频需求,然而,当用户需要将HTML页面或动态生成的HTML字符串转换为Wor... 目录引言一、html转Word的典型场景与挑战二、用 Spire.Doc 实现 HTML 转 Word1

C#实现一键批量合并PDF文档

《C#实现一键批量合并PDF文档》这篇文章主要为大家详细介绍了如何使用C#实现一键批量合并PDF文档功能,文中的示例代码简洁易懂,感兴趣的小伙伴可以跟随小编一起学习一下... 目录前言效果展示功能实现1、添加文件2、文件分组(书签)3、定义页码范围4、自定义显示5、定义页面尺寸6、PDF批量合并7、其他方法

C#下Newtonsoft.Json的具体使用

《C#下Newtonsoft.Json的具体使用》Newtonsoft.Json是一个非常流行的C#JSON序列化和反序列化库,它可以方便地将C#对象转换为JSON格式,或者将JSON数据解析为C#对... 目录安装 Newtonsoft.json基本用法1. 序列化 C# 对象为 JSON2. 反序列化

C#文件复制异常:"未能找到文件"的解决方案与预防措施

《C#文件复制异常:未能找到文件的解决方案与预防措施》在C#开发中,文件操作是基础中的基础,但有时最基础的File.Copy()方法也会抛出令人困惑的异常,当targetFilePath设置为D:2... 目录一个看似简单的文件操作问题问题重现与错误分析错误代码示例错误信息根本原因分析全面解决方案1. 确保

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

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

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

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

C# LiteDB处理时间序列数据的高性能解决方案

《C#LiteDB处理时间序列数据的高性能解决方案》LiteDB作为.NET生态下的轻量级嵌入式NoSQL数据库,一直是时间序列处理的优选方案,本文将为大家大家简单介绍一下LiteDB处理时间序列数... 目录为什么选择LiteDB处理时间序列数据第一章:LiteDB时间序列数据模型设计1.1 核心设计原则

Python 基于http.server模块实现简单http服务的代码举例

《Python基于http.server模块实现简单http服务的代码举例》Pythonhttp.server模块通过继承BaseHTTPRequestHandler处理HTTP请求,使用Threa... 目录测试环境代码实现相关介绍模块简介类及相关函数简介参考链接测试环境win11专业版python

Python从Word文档中提取图片并生成PPT的操作代码

《Python从Word文档中提取图片并生成PPT的操作代码》在日常办公场景中,我们经常需要从Word文档中提取图片,并将这些图片整理到PowerPoint幻灯片中,手动完成这一任务既耗时又容易出错,... 目录引言背景与需求解决方案概述代码解析代码核心逻辑说明总结引言在日常办公场景中,我们经常需要从 W

使用Spring Cache本地缓存示例代码

《使用SpringCache本地缓存示例代码》缓存是提高应用程序性能的重要手段,通过将频繁访问的数据存储在内存中,可以减少数据库访问次数,从而加速数据读取,:本文主要介绍使用SpringCac... 目录一、Spring Cache简介核心特点:二、基础配置1. 添加依赖2. 启用缓存3. 缓存配置方案方案