C#计算器

worldhj1 2010-01-07 09:19:02
有没有带括号的计算器。实在不知道如何进行写。

另外如果我有个表达式是
string a="如果(5>3)那么(a=4)否则(a=2)如果(5<2)那么(a=1)否则()"
用什么方法结合计算器算出值。如果可以多个,也可以套在否则中。

...全文
3011 30 打赏 收藏 转发到动态 举报
写回复
用AI写文章
30 条回复
切换为时间正序
请发表友善的回复…
发表回复
why_zz007 2010-01-09
  • 打赏
  • 举报
回复
简单点 if else就可以了
林三一 2010-01-09
  • 打赏
  • 举报
回复
学一下编译原理里的那叫编译器的东西就可以了。
shighui 2010-01-09
  • 打赏
  • 举报
回复
学一下编译原理里的那叫编译器的东西就可以了。
messi_yang 2010-01-09
  • 打赏
  • 举报
回复
邏輯算法問題。
Shift2010 2010-01-09
  • 打赏
  • 举报
回复
呵呵 无语
liherun 2010-01-09
  • 打赏
  • 举报
回复
[Quote=引用 24 楼 jiyuanlong 的回复:]
            string a = "如果(5>3)那么(a=4)否则(a=2)";
            a = a.Replace("如果", "if");
            a = a.Replace("那么", "{");
            a = a.Replace("否则", ";}else{");
            a = a + ";}";
然后包在一个静态方法里,用C#动态编译去执行。至于if嵌套,自己去解析吧。
[/Quote]
这都行,学习
元宇宙之家 2010-01-09
  • 打赏
  • 举报
回复
string a = "如果(5>3)那么(a=4)否则(a=2)";
a = a.Replace("如果", "if");
a = a.Replace("那么", "{");
a = a.Replace("否则", ";}else{");
a = a + ";}";
然后包在一个静态方法里,用C#动态编译去执行。至于if嵌套,自己去解析吧。
yingkk 2010-01-08
  • 打赏
  • 举报
回复
只要能在改改和设计下,就能像编程一样来计算,
pywepe 2010-01-08
  • 打赏
  • 举报
回复
真的呢
mytimes_walker 2010-01-08
  • 打赏
  • 举报
回复
[Quote=引用 4 楼 worldhj1 的回复:]
呵呵。只是随便举个例子。5>3明显是false
[/Quote]
5>3是false,那么3>5就是True了?
meadking 2010-01-08
  • 打赏
  • 举报
回复
用堆栈,把这个中缀表达式改为后缀表达式..(根据运算符的优先级)
基础的算法书里面都有!
我用Java实现过一个计算器.
MaraSun 2010-01-08
  • 打赏
  • 举报
回复
我实现了一个,好像与标准语法的不同,回避了什么符号栈等等问题,算法通俗易懂哦。优先级的运算也是非常的简单。如果需要代码,可向本人联系。因为本人已经将代码转换到了PB,因此C#部分没有继续维护。
laoas 2010-01-08
  • 打赏
  • 举报
回复
简单点 if else就可以了
元宇宙之家 2010-01-08
  • 打赏
  • 举报
回复
if() // 如果
{
// 那么
}
else
{
// 否则
}
tianliang1 2010-01-08
  • 打赏
  • 举报
回复
哎呀,大家都可以从网上拷贝一段代码给你,何不自助?
wuyi8808 2010-01-08
  • 打赏
  • 举报
回复
如果需要 C# 语法的,使用下面这个:
// Expression.cs - 动态生成数学表达式并计算其值 
// 表达式使用 C# 语法,可带一个的自变量(x)。
// 表达式的自变量和值均为(double)类型。
// 使用举例:
// Expression expression = new Expression("Math.Sin(x)");
// Console.WriteLine(expression.Compute(Math.PI / 2));
// expression = new Expression("double u = Math.PI - x;" +
// "double pi2 = Math.PI * Math.PI;" +
// "return 3 * x * x + Math.Log(u * u) / pi2 / pi2 + 1;");
// Console.WriteLine(expression.Compute(0));

using System;
using System.CodeDom.Compiler;
using Microsoft.CSharp;
using System.Reflection;
using System.Text;

namespace Skyiv.Util
{
sealed class Expression
{
object instance;
MethodInfo method;

public Expression(string expression)
{
if (expression.IndexOf("return") < 0) expression = "return " + expression + ";";
string className = "Expression";
string methodName = "Compute";
CompilerParameters p = new CompilerParameters();
p.GenerateInMemory = true;
CompilerResults cr = new CSharpCodeProvider().CompileAssemblyFromSource(p, string.
Format("using System;sealed class {0}{{public double {1}(double x){{{2}}}}}",
className, methodName, expression));
if(cr.Errors.Count > 0)
{
string msg = "Expression(\"" + expression + "\"): \n";
foreach (CompilerError err in cr.Errors) msg += err.ToString() + "\n";
throw new Exception(msg);
}
instance = cr.CompiledAssembly.CreateInstance(className);
method = instance.GetType().GetMethod(methodName);
}

public double Compute(double x)
{
return (double)method.Invoke(instance, new object [] { x });
}
}
}
wuyi8808 2010-01-08
  • 打赏
  • 举报
回复
// SuperCalc.cs - 超级计算器
// 编译方法: csc /t:winexe SuperCalc.cs VBExpression.cs

using System;
using System.Windows.Forms;
using Skyiv.Util;

namespace Skyiv
{
class Calc : Form
{
TextBox tbxA1;
TextBox tbxA3;

Calc()
{
Text = "Super Calculator";
StartPosition = FormStartPosition.CenterScreen;
Width = 300;
Height = 300;

tbxA1 = new TextBox();
tbxA1.Parent = this;
tbxA1.Multiline = true;
tbxA1.WordWrap = false;
tbxA1.Dock = DockStyle.Fill;
tbxA1.BorderStyle = BorderStyle.FixedSingle;

Panel pnlA1 = new Panel();
pnlA1.Parent = this;
pnlA1.Height = 22;
pnlA1.Dock = DockStyle.Top;

tbxA3 = new TextBox();
tbxA3.Parent = pnlA1;
tbxA3.Dock = DockStyle.Fill;
tbxA3.BorderStyle = BorderStyle.FixedSingle;
tbxA3.ReadOnly = true;

Button btnA3 = new Button();
btnA3.Text = "&Calculate";
btnA3.Parent = pnlA1;
btnA3.Width = 80;
btnA3.Dock = DockStyle.Left;
btnA3.Click += new EventHandler(Calc_Clicked);
}

void Calc_Clicked(object sender, EventArgs ea)
{
(sender as Control).Enabled = false;
try
{
tbxA3.Text = (new Expression(tbxA1.Text)).Compute().ToString();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error");
}
finally
{
(sender as Control).Enabled = true;
}
}

[STAThread]
static void Main(string [] args)
{
Application.Run(new Calc());
}
}
}


// VBExpression.cs - 动态生成数学表达式并计算其值
// 表达式使用 Visual Baisc 语法
// 可使用 pi、e 等常量,sin、cos、tan、log、sqrt 等函数

using System;
using System.CodeDom.Compiler;
using Microsoft.VisualBasic;
using System.Reflection;
using System.Text;
using System.Globalization;

namespace Skyiv.Util
{
sealed class Expression
{
object instance;
MethodInfo method;

public Expression(string expression)
{
if (expression.ToUpper(CultureInfo.InvariantCulture).IndexOf("RETURN") < 0)
{
expression = "Return " + expression.Replace(Environment.NewLine, " ");
}
string className = "Expression";
string methodName = "Compute";
CompilerParameters p = new CompilerParameters();
p.GenerateInMemory = true;
CompilerResults cr = new VBCodeProvider().CompileAssemblyFromSource
(
p,
string.Format
(
@"Option Explicit Off
Option Strict Off
Imports System, System.Math, Microsoft.VisualBasic
NotInheritable Class {0}
Public Function {1} As Double
{2}
End Function
End Class",
className, methodName, expression
)
);
if(cr.Errors.Count > 0)
{
string msg = "Expression(\"" + expression + "\"): \n";
foreach (CompilerError err in cr.Errors) msg += err.ToString() + "\n";
throw new Exception(msg);
}
instance = cr.CompiledAssembly.CreateInstance(className);
method = instance.GetType().GetMethod(methodName);
}

public double Compute()
{
return (double)method.Invoke(instance, null);
}
}
}
yingkk 2010-01-07
  • 打赏
  • 举报
回复
晕,发错了
yingkk 2010-01-07
  • 打赏
  • 举报
回复
开头定义

using System.CodeDom;
using System.CodeDom.Compiler;
using System.Diagnostics;
using Microsoft.CSharp;
using System.IO;

加个按钮
文本框tb_content.Text: 输入计算公式,比如(6*12>2?(1-9):0)
标签lb_result:显示结果

按钮里面代码

private void bn_calculate_Click(object sender, EventArgs e)
{
string beginTxt = "namespace calculator{class Program{static void Main(string[] args){ System.Console.WriteLine(";
string endTxt = tb_content.Text + ");}}}";
CSharpCodeProvider codeProvider = new CSharpCodeProvider();
ICodeCompiler icc = codeProvider.CreateCompiler();
string Output = "Out.exe";
Button ButtonObject = (Button)sender;

System.CodeDom.Compiler.CompilerParameters parameters = new CompilerParameters();
//Make sure we generate an EXE, not a DLL
parameters.GenerateExecutable = true;
parameters.OutputAssembly = Output;
CompilerResults results = icc.CompileAssemblyFromSource(parameters, beginTxt+endTxt);

if (results.Errors.Count > 0)
{
lb_result.ForeColor = Color.Red;
foreach (CompilerError CompErr in results.Errors)
{
lb_result.Text = lb_result.Text +
"Line number " + CompErr.Line +
", Error Number: " + CompErr.ErrorNumber +
", '" + CompErr.ErrorText + ";" +
Environment.NewLine + Environment.NewLine;
}
}
else
{
string myString = "Noting";
//Successful Compile
lb_result.ForeColor = Color.Blue;
lb_result.Text = "Success!";

Process myProcess = new Process();
ProcessStartInfo myProcessStartInfo = new ProcessStartInfo(Output);
myProcessStartInfo.UseShellExecute = false;
myProcessStartInfo.RedirectStandardOutput = true;
myProcess.StartInfo = myProcessStartInfo;
myProcess.Start();

StreamReader myStreamReader = myProcess.StandardOutput;
// Read the standard output of the spawned process.
myString = myStreamReader.ReadToEnd();

myProcess.Close();
lb_result.Text = myString;

}

}


结果就是:
加载更多回复(10)

110,545

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧