Új hozzászólás Aktív témák

  • Lacces

    őstag

    Nos, köszönöm, a helpet, igyekeztem megírni a stuki alapján a kódot.

    Valami nem stimmel az algoritmussal, (hosszabb bemeneti sztringeknél vettem észre)

    Mert ezt kellene kapnom:
    5 1 2 + 4 * + 3 -
    De helyeztte ez jön ki...
    5 1 2 + 4 * 3 - +

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Collections;

    namespace LengyelForma
    {
    class LengyelForma
    {
    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)
    {
    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))
    {
    formula.Append(x);
    }
    else if (IsOperator(x))
    {
    while (stack.Count > 0 && (char)stack.Peek() != '(' && Prior(x) >= Prior((char)stack.Peek()))
    {
    char y = (char)stack.Pop();
    formula.Append(y);
    }
    while (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();
    if(c!='(')
    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");
    }
    }
    }

    }

Új hozzászólás Aktív témák