逆波兰表示法 C# 无法正常工作

发布于 2024-12-10 14:39:34 字数 2968 浏览 1 评论 0原文

我写了一个 rpn,带有一个结构图。

最新问题:现在无法正常工作。

如果输入字符串是“5 + ((1 + 2) * 4) - 3”

我的输出是: 5 1 2 + 4 * 3 - +

我必须得到这个结果: 5 1 2 + 4 * + 3 -

编辑源

*那是原来的问题,但对我有帮助,现在原来的错误已修复:*

在调试时循环或 int i = 12,c值为0\0或其他 并且这个值被添加到输出(名称:公式)字符串作为“(”括号。我不知道为什么。 最后一个'-'运算符号,不要添加到(或不看)输出字符串(公式)的末尾 我错误地认为这个问题是由“(”引起的。 我尝试了使用其他字符串输入值的程序,但总是在我的字符串中添加一个“(”,我不知道为什么......我看到它与括号的数量无关。总是只有一个“ (' 添加到我的字符串...*) 是的,英语 LengyelFormula = rpn (匈牙利语)*

static void Main(string[] args)
    {
        String str = "5 + ( ( 1 + 2 ) *  4 ) −3";
        String result=LengyelFormaKonvertalas(str);
        Console.WriteLine(result.ToString());
        Console.ReadLine();
    }

    static String LengyelFormaKonvertalas(String input) // this is the rpn method
    {
       Stack stack = new Stack();
       String str = input.Replace(" ",string.Empty);
       StringBuilder formula = new StringBuilder();
       for (int i = 0; i < str.Length; i++)
       {
           char x=str[i];
           if (x == '(')
               stack.Push(x);
           else if (IsOperandus(x)) // is it operand
           {
               formula.Append(x);
           }
           else if (IsOperator(x))  // is it operation
           {
               if (stack.Count>0 && (char)stack.Peek()!='(' && Prior(x)<=Prior((char)stack.Peek()) )
               {
                   char y = (char)stack.Pop();
                   formula.Append(y);
               }
               if (stack.Count > 0 && (char)stack.Peek() != '(' && Prior(x) < Prior((char)stack.Peek()))
               {
                   char y = (char)stack.Pop();
                   formula.Append(y);
               }
               stack.Push(x);
           }
           else
           {
              char y=(char)stack.Pop();
              if (y!='(')
              {
                  formula.Append(y);
              }
           }
       }
       while (stack.Count>0)
       {
           char c = (char)stack.Pop();
           formula.Append(c);
       }
       return formula.ToString();
    }

    static bool IsOperator(char c)
    {
        return (c=='-'|| c=='+' || c=='*' || c=='/');
    }
    static bool IsOperandus(char c)
    {
        return (c>='0' && c<='9' || c=='.');
    }
    static int Prior(char c)
    {
        switch (c)
        {
            case '=':
                return 1;
            case '+':
                return 2;
            case '-':
                return 2;
            case '*':
                return 3;
            case '/':
                return 3;
            case '^':
                return 4;
            default:
                throw new ArgumentException("Rossz paraméter");                                          
        }
    }
}

I write an rpn, with a struktogram.

Newest Problem: It is'nt work correctly now.

If input string is "5 + ((1 + 2) * 4) - 3"

My output is:
5 1 2 + 4 * 3 - +

I have to got this result:
5 1 2 + 4 * + 3 -

Edited the source

*That was the original problem, but helped me, and now the original mistakes fixed: *,

At the debug when the loop or
int i = 12, the c value is 0\0 or something else
and this value is added to output (name: formula) string as a '(' bracket. And I don't know why.
And the last '-' operation symbol, don't added to (or not look) at the end of output string (formula)
I misgave this problem cause by the '('.
I tried the program with other string input value, but always put an '(' to my string, and I don't know why... I saw that It was independt about the numbers of bracket. Always only one '(' add to my string...*)
Yes, in english LengyelFormula = rpn (it is hungarian)*

static void Main(string[] args)
    {
        String str = "5 + ( ( 1 + 2 ) *  4 ) −3";
        String result=LengyelFormaKonvertalas(str);
        Console.WriteLine(result.ToString());
        Console.ReadLine();
    }

    static String LengyelFormaKonvertalas(String input) // this is the rpn method
    {
       Stack stack = new Stack();
       String str = input.Replace(" ",string.Empty);
       StringBuilder formula = new StringBuilder();
       for (int i = 0; i < str.Length; i++)
       {
           char x=str[i];
           if (x == '(')
               stack.Push(x);
           else if (IsOperandus(x)) // is it operand
           {
               formula.Append(x);
           }
           else if (IsOperator(x))  // is it operation
           {
               if (stack.Count>0 && (char)stack.Peek()!='(' && Prior(x)<=Prior((char)stack.Peek()) )
               {
                   char y = (char)stack.Pop();
                   formula.Append(y);
               }
               if (stack.Count > 0 && (char)stack.Peek() != '(' && Prior(x) < Prior((char)stack.Peek()))
               {
                   char y = (char)stack.Pop();
                   formula.Append(y);
               }
               stack.Push(x);
           }
           else
           {
              char y=(char)stack.Pop();
              if (y!='(')
              {
                  formula.Append(y);
              }
           }
       }
       while (stack.Count>0)
       {
           char c = (char)stack.Pop();
           formula.Append(c);
       }
       return formula.ToString();
    }

    static bool IsOperator(char c)
    {
        return (c=='-'|| c=='+' || c=='*' || c=='/');
    }
    static bool IsOperandus(char c)
    {
        return (c>='0' && c<='9' || c=='.');
    }
    static int Prior(char c)
    {
        switch (c)
        {
            case '=':
                return 1;
            case '+':
                return 2;
            case '-':
                return 2;
            case '*':
                return 3;
            case '/':
                return 3;
            case '^':
                return 4;
            default:
                throw new ArgumentException("Rossz paraméter");                                          
        }
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

东走西顾 2024-12-17 14:39:34
using System;
using System.Collections.Generic;
using System.Text;

class Sample {
    static void Main(string[] args){
        String str = "5 + ( ( 1 + 2 ) *  4 ) -3";
        String result=LengyelFormaKonvertalas(str);
        Console.WriteLine(result);
        Console.ReadLine();
    }

    static String LengyelFormaKonvertalas(String input){
       Stack<char> stack = new Stack<char>();
       String str = input.Replace(" ", string.Empty);
       StringBuilder formula = new StringBuilder();
       for (int i = 0; i < str.Length; i++){
           char x=str[i];
           if (x == '(')
               stack.Push(x);
           else if (x == ')'){
               while(stack.Count>0 && stack.Peek() != '(')
                   formula.Append(stack.Pop());
               stack.Pop();
           } else if (IsOperandus(x)){
               formula.Append(x);
           } else if (IsOperator(x)) {
               while(stack.Count>0 && stack.Peek() != '(' && Prior(x)<=Prior(stack.Peek()) )
                   formula.Append(stack.Pop());
               stack.Push(x);
           }
           else {
              char y= stack.Pop();
              if (y!='(') 
                  formula.Append(y);
           }
       }
       while (stack.Count>0) {
           formula.Append(stack.Pop());
       }
       return formula.ToString();
    }

    static bool IsOperator(char c){
        return (c=='-'|| c=='+' || c=='*' || c=='/');
    }
    static bool IsOperandus(char c){
        return (c>='0' && c<='9' || c=='.');
    }
    static int Prior(char c){
        switch (c){
            case '=':
                return 1;
            case '+':
                return 2;
            case '-':
                return 2;
            case '*':
                return 3;
            case '/':
                return 3;
            case '^':
                return 4;
            default:
                throw new ArgumentException("Rossz parameter");                                          
        }
    }
}
using System;
using System.Collections.Generic;
using System.Text;

class Sample {
    static void Main(string[] args){
        String str = "5 + ( ( 1 + 2 ) *  4 ) -3";
        String result=LengyelFormaKonvertalas(str);
        Console.WriteLine(result);
        Console.ReadLine();
    }

    static String LengyelFormaKonvertalas(String input){
       Stack<char> stack = new Stack<char>();
       String str = input.Replace(" ", string.Empty);
       StringBuilder formula = new StringBuilder();
       for (int i = 0; i < str.Length; i++){
           char x=str[i];
           if (x == '(')
               stack.Push(x);
           else if (x == ')'){
               while(stack.Count>0 && stack.Peek() != '(')
                   formula.Append(stack.Pop());
               stack.Pop();
           } else if (IsOperandus(x)){
               formula.Append(x);
           } else if (IsOperator(x)) {
               while(stack.Count>0 && stack.Peek() != '(' && Prior(x)<=Prior(stack.Peek()) )
                   formula.Append(stack.Pop());
               stack.Push(x);
           }
           else {
              char y= stack.Pop();
              if (y!='(') 
                  formula.Append(y);
           }
       }
       while (stack.Count>0) {
           formula.Append(stack.Pop());
       }
       return formula.ToString();
    }

    static bool IsOperator(char c){
        return (c=='-'|| c=='+' || c=='*' || c=='/');
    }
    static bool IsOperandus(char c){
        return (c>='0' && c<='9' || c=='.');
    }
    static int Prior(char c){
        switch (c){
            case '=':
                return 1;
            case '+':
                return 2;
            case '-':
                return 2;
            case '*':
                return 3;
            case '/':
                return 3;
            case '^':
                return 4;
            default:
                throw new ArgumentException("Rossz parameter");                                          
        }
    }
}
江挽川 2024-12-17 14:39:34

在 IsOperator 中,您检查 c == '-'。
但在字符串中,你写 -3。
− 与 -
不是同一字符
我不知道波兰语的东西,所以也许我遗漏了一些东西,但这就是为什么没有打印“-”运算符,它未通过 IsOperator 检查并进入 else 子句,该子句不会将其添加到公式中。

In IsOperator, you check c == '-'.
But in the string, you write −3.
− isn't the same character than -
I don't know about Polish stuff so maybe I'm missing something, but that's why no '-' operator is printed, it fails the IsOperator check and goes into the else clause, which doesn't add it to formula.

吻泪 2024-12-17 14:39:34

当您得到 ) 时,您应该弹出所有运算符并将它们添加到公式中,直到到达 (,并弹出“(”。

当您得到运算符,只有当其优先级大于或等于 x 时,才应弹出堆栈并将该运算符添加到公式中。第二个检查是多余的,因为它已被第一个

As 覆盖。一般规则:使用一些简单的输入来尝试您的程序,例如1+2+31+2-31*2+31+2*3 > 看看您是否得到正确的结果,这样可以帮助您更快地发现错误。

When you get a ), you should pop all operators and add them to your formula until you reach a (, and pop that '(' as well.

When you get an operator, you should only pop the stack and add this operator to the formula if its priority is greater than or equal to that of x. Your second check is redundant because it is already covered by the first.

As a general rule: try your program with some simple inputs like 1+2+3, 1+2-3, 1*2+3 and 1+2*3 and see if you get the right result. Testing systematically like that should help you find errors faster.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文