C# 用c语言求解后缀符号表达式#
我有一个任务是从中缀创建后缀符号。我让代码正常工作,我有一个后缀符号字符串,但我不知道如何从中得到答案。我可以调用.NET方法吗?我试着用谷歌搜索这个问题,但只能找到如何将其更改为post fix 非常感谢您的帮助 更新 我需要找到一个表达式的答案,比如:12+3-4+5-C# 用c语言求解后缀符号表达式#,c#,expression,postfix-notation,C#,Expression,Postfix Notation,我有一个任务是从中缀创建后缀符号。我让代码正常工作,我有一个后缀符号字符串,但我不知道如何从中得到答案。我可以调用.NET方法吗?我试着用谷歌搜索这个问题,但只能找到如何将其更改为post fix 非常感谢您的帮助 更新 我需要找到一个表达式的答案,比如:12+3-4+5- 我希望找到一个更简单的方法来实现这一点,但我没有,所以我写了自己的方法。如果允许的话,我将在8小时内发布。Postfix是字符串中的表达式,如“109+7%3-” postfix=postfix.Trim(); 字符串[]a
我希望找到一个更简单的方法来实现这一点,但我没有,所以我写了自己的方法。如果允许的话,我将在8小时内发布。Postfix是字符串中的表达式,如“109+7%3-”
postfix=postfix.Trim();
字符串[]ans=postfix.Split(“”);
堆栈评估=新堆栈();
对于(int x=0;x
//过早地切断代码。for语句完成后,执行的答案将是int-answer=eval.Pop() 后缀是字符串中的表达式,如“109+7%3-”
postfix=postfix.Trim();
字符串[]ans=postfix.Split(“”);
堆栈评估=新堆栈();
对于(int x=0;x
//过早地切断代码。for语句完成后,执行的答案将是int-answer=eval.Pop() 使用系统;
使用System.Collections.Generic;
使用System.Linq;
使用系统文本;
使用系统集合;
名称空间pof
{
eva级
{
公共字符串po;
公共字符串应答;
堆栈i=新堆栈();
公共空间e()
{
INTA,b,ans;
对于(int j=0;jpostfix = postfix.Trim();
string[] ans = postfix.Split(' ');
Stack<int> eval = new Stack<int>();
for (int x = 0; x < ans.Length; x++)
{
if ("*+%/-".Contains(ans[x]))
{
int temp1;
int temp2;
switch (ans[x])
{
case ("*"):
eval.Push(eval.Pop() * eval.Pop());
break;
case "-":
temp1 = eval.Pop();
temp2 = eval.Pop();
eval.Push(temp2 - temp1);
break;
case "%":
temp1 = eval.Pop();
temp2 = eval.Pop();
eval.Push(temp2 % temp1);
break;
case "+":
eval.Push(eval.Pop() + eval.Pop());
break;
case "/":
temp1 = eval.Pop();
temp2 = eval.Pop();
eval.Push(temp2 / temp1);
break;
}
}
else
eval.Push(Convert.ToInt32(ans[x]));
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace pof
{
class eva
{
public string po;
public string answer;
Stack i = new Stack();
public void e()
{
int a, b, ans;
for (int j = 0; j < po.Length; j++)
{
String c = po.Substring(j, 1);
if (c.Equals ("*"))
{
String sa = (String)i.Pop();
String sb = (String)i.Pop();
a = Convert.ToInt32(sb);
b = Convert.ToInt32(sa);
ans = a * b;
i.Push(ans.ToString());
}
else if (c.Equals("/"))
{
String sa = (String)i.Pop();
String sb = (String)i.Pop();
a = Convert.ToInt32(sb);
b = Convert.ToInt32(sa);
ans = a / b;
i.Push(ans.ToString());
}
else if (c.Equals("+"))
{
String sa = (String)i.Pop();
String sb = (String)i.Pop();
a = Convert.ToInt32(sb);
b = Convert.ToInt32(sa);
ans = a + b;
i.Push(ans.ToString());
}
else if (c.Equals("-"))
{
String sa = (String)i.Pop();
String sb = (String)i.Pop();
a = Convert.ToInt32(sb);
b = Convert.ToInt32(sa);
ans = a - b;
i.Push(ans.ToString());
}
else
{
i.Push(po.Substring(j, 1));
}
}
answer=(String)i.Pop();
}
}
class Program
{
static void Main(string[] args)
{
eva e1 = new eva();
Console.WriteLine("enter any postfix expression");
e1.po = Console.ReadLine();
e1.e();
Console.WriteLine("\n\t\tpostfix evaluation: " + e1.answer);
Console.ReadKey();
}
}
}