Форум программистов, компьютерный форум, киберфорум
C# для начинающих
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.73/11: Рейтинг темы: голосов - 11, средняя оценка - 4.73
1 / 1 / 0
Регистрация: 17.10.2021
Сообщений: 169

Обратная польская нотация

28.02.2022, 13:54. Показов 2112. Ответов 2
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Составьте свое выражение, записанное в обратной польской нотации, и вычислите его значение. Предусмотреть ввод переменных с клавиатуры.
Обратная польская нотация — это форма записи математических выражений, в которой операторы расположены после своих операндов.
Буду очень признателен если кто поможет
0
Лучшие ответы (1)
Programming
Эксперт
39485 / 9562 / 3019
Регистрация: 12.04.2006
Сообщений: 41,671
Блог
28.02.2022, 13:54
Ответы с готовыми решениями:

Обратная польская запись
Вычислить выражение состоящее из цифр, скобок,знаков операций (+, -, *,/) записанное в виде: обратной польской записи.

Польская обратная запись
Народ, спасайте, препод зверюга... Просит написать программу... Калькулятор с Польской обратной записью, но! Не используя стек. Мы прошли...

Обратная польская запись
Вопрос таков. Нужно преобразовать строку типа string в обратную польскую запись. Пример "a-(b*c)" Спасибо

2
Эксперт JavaЭксперт по электроникеЭксперт .NET
 Аватар для wizard41
3409 / 2730 / 575
Регистрация: 04.09.2018
Сообщений: 8,567
Записей в блоге: 3
28.02.2022, 14:49
Лучший ответ Сообщение было отмечено Joseph_Seed как решение

Решение

Joseph_Seed,
class RPN
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
    internal class RPN
    {
        /// <summary>
        /// The method returns true if the checked character is a separator ("space" or "equal")
        /// </summary>
        static private bool IsDelimeter( char c )
        {
            if ( ( " =".IndexOf( c ) != -1 ) )
                return true;
            return false;
        }
 
 
        /// <summary>
        /// The method returns true if the checked character is an operator
        /// </summary>
        static private bool IsOperator( char с )
        {
            if ( ( "+-/*^()".IndexOf( с ) != -1 ) )
                return true;
            return false;
        }
 
 
        /// <summary>
        /// The method returns the operator priority
        /// </summary>
        static private byte GetPriority( char s )
        {
            byte b = s switch
            {
                '(' => 0,
                ')' => 1,
                '+' => 2,
                '-' => 3,
                '*' => 4,
                '/' => 4,
                '^' => 5,
                _ => 6
            };
            return b;
        }
 
 
        /// <summary>
        /// The "input" method of the class
        /// </summary>
        static public double Calculate( string input )
        {
            string output = GetExpression( input ); // Converting the expression to a postfix entry
            double result = Counting( output ); // Solving the resulting expression
            return result;
        }
 
 
        /// <summary>
        /// Get Expression
        /// </summary>
        static private string GetExpression( string input )
        {
            string output = string.Empty; // String to store the expression
            Stack<char> operStack = new Stack<char>(); // Stack for storing operators
 
            // For each character in the input string
            for ( int i = 0; i < input.Length; i++ ) 
            {
                // We skip the separators
                if ( IsDelimeter( input[ i ] ) )
                    continue; // Moving on to the next character
 
                // If the symbol is a digit, then we read the whole number
                if ( Char.IsDigit( input[ i ] ) ) //Если цифра
                {
                    // We read up to the separator or operator to get the number
                    while ( !IsDelimeter( input[ i ] ) && !IsOperator( input[ i ] ) )
                    {
                        // Adding each digit of the number to our string
                        output += input[ i ]; 
                        i++; // Moving on to the next character
 
                        // If the symbol is the last one, then we exit the loop
                        if ( i == input.Length ) break; 
                    }
 
                    output += " "; // We add a space after the number to the string with the expression
                    i--; // Going back one character to the character before the separator
                }
 
                // If the symbol is an operator
                if ( IsOperator( input[ i ] ) ) // If the operator
                {
                    if ( input[ i ] == '(' ) // If the character is an opening parenthesis
                        operStack.Push( input[ i ] ); // We write it to the stack
                    else if ( input[ i ] == ')' ) // If the character is a closing parenthesis
                    {
                        // We write out all the operators up to the opening parenthesis in the string
                        char s = operStack.Pop();
 
                        while ( s != '(' )
                        {
                            output += s.ToString() + ' ';
                            s = operStack.Pop();
                        }
                    }
                    else // If any other operator
                    {
                        // If there are elements in the stack
                        if ( operStack.Count > 0 )
 
                            // And if the priority of our operator is less than or equal to the priority of the operator at the top of the stack
                            if ( GetPriority( input[ i ] ) <= GetPriority( operStack.Peek() ) )
 
                                // Then we add the last operator from the stack to the string with the expression
                                output += operStack.Pop().ToString() + " ";
 
                        // If the stack is empty, or the operator's priority is higher, we add operators to the top of the stack
                        operStack.Push( char.Parse( input[ i ].ToString() ) );
 
                    }
                }
            }
 
            // When we have passed through all the characters, we throw all the remaining operators out of the stack into a string
            while ( operStack.Count > 0 )
                output += operStack.Pop() + " ";
 
            // Returning the expression in the postfix entry
            return output;
        }
 
 
        /// <summary>
        /// Calculation
        /// </summary>
        static private double Counting( string input )
        {
            double result = 0;
            Stack<double> temp = new Stack<double>(); // Stack for solution
 
            for ( int i = 0; i < input.Length; i++ ) // For each character in the string
            {
                // If the symbol is a digit, then we read the whole number and write it to the top of the stack
                if ( Char.IsDigit( input[ i ] ) )
                {
                    string a = string.Empty;
 
                    while ( !IsDelimeter( input[ i ] ) && !IsOperator( input[ i ] ) ) // Not yet a separator
                    {
                        a += input[ i ]; // Adding
                        i++;
                        if ( i == input.Length ) break;
                    }
                    temp.Push( double.Parse( a ) ); // Writing to the stack
                    i--;
                }
                else if ( IsOperator( input[ i ] ) ) // If the symbol is an operator
                {
                    // We take the last two values from the stack
                    double a = temp.Pop();
                    double b = temp.Pop();
 
                    switch ( input[ i ] ) // And we perform an action on them, according to the operator
                    {
                        case '+': result = b + a; break;
                        case '-': result = b - a; break;
                        case '*': result = b * a; break;
                        case '/': result = b / a; break;
                        case '^': result = double.Parse( Math.Pow( double.Parse( b.ToString() ), double.Parse( a.ToString() ) ).ToString() ); break;
                    }
                    temp.Push( result ); // The result of the calculation is written back to the stack
                }
            }
            return temp.Peek(); // We take the result of all calculations from the stack and return it
        }
    }

Using it:
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
            Console.WriteLine( "<--- Reverse Polish Notation --->" );
 
            Console.WriteLine( "\nA few examples of expressions:" );
            string expr = "8 + (5 * 4) - 12 + (3 * 7)";
            Console.WriteLine( $"{expr} = {RPN.Calculate( expr )}" );
            expr = "5^2 + 55 * (9 / 3)";
            Console.WriteLine( $"{expr} = {RPN.Calculate( expr )}" );
            expr = "3/2 + 5/2 + 7/2";
            Console.WriteLine( $"{expr} = {RPN.Calculate( expr )}" );
 
            Console.Write( "Enter expression: " );
            expr = Console.ReadLine();
            Console.WriteLine( $"{expr} = {RPN.Calculate( expr )}" );
2
1 / 1 / 0
Регистрация: 17.10.2021
Сообщений: 169
28.02.2022, 14:51  [ТС]
wizard41, Благодарю огромное спасибо
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
inter-admin
Эксперт
29715 / 6470 / 2152
Регистрация: 06.03.2009
Сообщений: 28,500
Блог
28.02.2022, 14:51
Помогаю со студенческими работами здесь

Обратная польская запись
Помогите написать программу преобразования выражения в ОПЗ с помощью стэка на С#

Обратная польская запись
Добрый день! Нужна ваша помощь. Процедура не правильно выводит обратную польскую запись. Что нужно изменить? public string...

Обратная польская запись
В постфиксной записи (или обратной польской записи) операция записывается после двух операндов. Например, сумма двух чисел A и B...

Обратная польская запись деление на 0
Подскажите пожалуйста, как в данном коде сделать так, чтобы при делении на 0 получался ответ 0, а не бесконечность. static private double...

Калькулятор со скобками (обратная польская запись)
взял реализацию...сделанную по принципу ОПН ..нашел баг в проге..нещитает числа с запятыми начал переделывать и вот ошибка -- op2 =...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
3
Ответ Создать тему
Новые блоги и статьи
SDL3 для Web (WebAssembly): Реализация движения на Box2D v3 - трение и коллизии с повёрнутыми стенами
8Observer8 20.02.2026
Содержание блога Box2D позволяет легко создать главного героя, который не проходит сквозь стены и перемещается с заданным трением о препятствия, которые можно располагать под углом, как верхнее. . .
Конвертировать закладки radiotray-ng в m3u-плейлист
damix 19.02.2026
Это можно сделать скриптом для PowerShell. Использование . \СonvertRadiotrayToM3U. ps1 <path_to_bookmarks. json> Рядом с файлом bookmarks. json появится файл bookmarks. m3u с результатом. # Check if. . .
Семь CDC на одном интерфейсе: 5 U[S]ARTов, 1 CAN и 1 SSI
Eddy_Em 18.02.2026
Постепенно допиливаю свою "многоинтерфейсную плату". Выглядит вот так: https:/ / www. cyberforum. ru/ blog_attachment. php?attachmentid=11617&stc=1&d=1771445347 Основана на STM32F303RBT6. На борту пять. . .
Камера Toupcam IUA500KMA
Eddy_Em 12.02.2026
Т. к. у всяких "хикроботов" слишком уж мелкий пиксель, для подсмотра в ESPriF они вообще плохо годятся: уже 14 величину можно рассмотреть еле-еле лишь на экспозициях под 3 секунды (а то и больше),. . .
И ясному Солнцу
zbw 12.02.2026
И ясному Солнцу, и светлой Луне. В мире покоя нет и люди не могут жить в тишине. А жить им немного лет.
«Знание-Сила»
zbw 12.02.2026
«Знание-Сила» «Время-Деньги» «Деньги -Пуля»
SDL3 для Web (WebAssembly): Подключение Box2D v3, физика и отрисовка коллайдеров
8Observer8 12.02.2026
Содержание блога Box2D - это библиотека для 2D физики для анимаций и игр. С её помощью можно определять были ли коллизии между конкретными объектами и вызывать обработчики событий столкновения. . . .
SDL3 для Web (WebAssembly): Загрузка PNG с прозрачным фоном с помощью SDL_LoadPNG (без SDL3_image)
8Observer8 11.02.2026
Содержание блога Библиотека SDL3 содержит встроенные инструменты для базовой работы с изображениями - без использования библиотеки SDL3_image. Пошагово создадим проект для загрузки изображения. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru