Форум программистов, компьютерный форум, киберфорум
C# Windows Forms
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.94/18: Рейтинг темы: голосов - 18, средняя оценка - 4.94
1 / 11 / 0
Регистрация: 24.09.2016
Сообщений: 98

Ввод функции в Textbox

28.04.2017, 21:51. Показов 3534. Ответов 1
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Здравствуйте, мне необходимо реализовать ввод функции через текстбокс.
Начала писать код
C#
1
2
3
4
5
6
7
 private void Form1_Load(object sender, EventArgs e)
        {
            string input = (textBox1.Text); // строка которую нужно разобрать
            Function f = new Function(input); // создаем функцию
            double result;
            return result = f.calculate(x);
        }
и нашла код для распознавания самой функции
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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
public class Parser
  {
    public const char START_ARG = '(';
    public const char END_ARG   = ')';
    public const char END_LINE  = '\n';
 
    class Cell
    {
      internal Cell(double value, char action)
      {
        Value = value;
        Action = action;
      }
 
      internal double Value  { get; set; }
      internal char   Action { get; set; }
    }
 
    public static double process(string data)
    {
      // Get rid of spaces and check parenthesis
      string expression = preprocess(data);
      int from = 0;
 
      return loadAndCalculate(data, ref from, END_LINE);
    }
 
    static string preprocess(string data)
    {
      if (string.IsNullOrEmpty(data))
      {
        throw new ArgumentException("Loaded empty data");
      }
 
      int parentheses = 0;
      StringBuilder result = new StringBuilder(data.Length);
 
      for (int i = 0; i < data.Length; i++)
      {
        char ch = data[i];
        switch (ch)
        {
          case ' ':
          case '\t':
          case '\n': continue;
          case END_ARG:   parentheses--;
            break;
          case START_ARG: parentheses++;
            break;
        }
        result.Append(ch);
      }
 
      if (parentheses != 0)
      {
        throw new ArgumentException("Uneven parenthesis");
      }
 
      return result.ToString();
    }
 
    public static double loadAndCalculate(string data, ref int from, char to = END_LINE)
    {
      if (from >= data.Length || data[from] == to)
      {
        throw new ArgumentException("Loaded invalid data: " + data);
      }
 
      List<Cell> listToMerge = new List<Cell>(16);
      StringBuilder item = new StringBuilder();
 
      do
      { // Main processing cycle of the first part.
        char ch = data[from++];
        if (stillCollecting(item.ToString(), ch, to))
        { // The char still belongs to the previous operand.
          item.Append(ch);
          if (from < data.Length && data[from] != to)
          {
            continue;
          }
        }
 
        // We are done getting the next token. The getValue() call below may
        // recursively call loadAndCalculate(). This will happen if extracted
        // item is a function or if the next item is starting with a START_ARG '('.
        ParserFunction func = new ParserFunction(data, ref from, item.ToString(), ch);
        double value = func.getValue(data, ref from);
 
        char action = validAction(ch) ? ch
                                      : updateAction(data, ref from, ch, to);
 
        listToMerge.Add(new Cell(value, action));
        item.Clear();
 
      } while (from < data.Length && data[from] != to);
 
      if (from < data.Length &&
         (data[from] == END_ARG || data[from] == to))
      { // This happens when called recursively: move one char forward.
        from++;
      }
 
      Cell baseCell = listToMerge[0];
      int index = 1;
 
      return merge(baseCell, ref index, listToMerge);
    }
 
    static bool stillCollecting(string item, char ch, char to)
    {
      // Stop collecting if either got END_ARG ')' or to char, e.g. ','.
      char stopCollecting = (to == END_ARG || to == END_LINE) ?
                             END_ARG : to;
      return (item.Length == 0 && (ch == '-' || ch == END_ARG)) ||
            !(validAction(ch) || ch == START_ARG || ch == stopCollecting);
    }
 
    static bool validAction(char ch)
    {
      return ch == '*' || ch == '/' || ch == '+' || ch == '-' || ch == '^';
    }
 
    static char updateAction(string item, ref int from, char ch, char to)
    {
      if (from >= item.Length || item[from] == END_ARG || item[from] == to)
      {
        return END_ARG;
      }
 
      int index = from;
      char res = ch;
      while (!validAction(res) && index < item.Length)
      { // Look for the next character in string until a valid action is found.
        res = item[index++];
      }
 
      from = validAction(res) ? index
                              : index > from ? index - 1
                                             : from;
      return res;
    }
 
    // From outside this function is called with mergeOneOnly = false.
    // It also calls itself recursively with mergeOneOnly = true, meaning
    // that it will return after only one merge.
    static double merge(Cell current, ref int index, List<Cell> listToMerge,
                 bool mergeOneOnly = false)
    {
      while (index < listToMerge.Count)
      {
        Cell next = listToMerge[index++];
 
        while (!canMergeCells(current, next))
        { // If we cannot merge cells yet, go to the next cell and merge
          // next cells first. E.g. if we have 1+2*3, we first merge next
          // cells, i.e. 2*3, getting 6, and then we can merge 1+6.
          merge(next, ref index, listToMerge, true /* mergeOneOnly */);
        }
        mergeCells(current, next);
        if (mergeOneOnly)
        {
          return current.Value;
        }
      }
 
      return current.Value;
    }
 
    static void mergeCells(Cell leftCell, Cell rightCell)
    {
      switch (leftCell.Action)
      {
        case '^': leftCell.Value = Math.Pow(leftCell.Value, rightCell.Value);
          break;
        case '*': leftCell.Value *= rightCell.Value;
          break;
        case '/':
          if (rightCell.Value == 0)
          {
            throw new ArgumentException("Division by zero");
          }
          leftCell.Value /= rightCell.Value;
          break;
        case '+': leftCell.Value += rightCell.Value;
          break;
        case '-': leftCell.Value -= rightCell.Value;
          break;
      }
      leftCell.Action = rightCell.Action;
    }
 
    static bool canMergeCells(Cell leftCell, Cell rightCell)
    {
      return getPriority(leftCell.Action) >= getPriority(rightCell.Action);
    }
 
    static int getPriority(char action)
    {
      switch (action) {
        case '^': return 4;
        case '*':
        case '/': return 3;
        case '+':
        case '-': return 2;
      }
      return 0;
    }
  }
 
  public class ParserFunction
  {
    public ParserFunction()
    {
      m_impl = this;
    }
 
    // A "virtual" Constructor
    internal ParserFunction(string data, ref int from, string item, char ch)
    {
      if (item.Length == 0 && ch == Parser.START_ARG)
      {
        // There is no function, just an expression in parentheses
        m_impl = s_idFunction;
        return;
      }
 
      if (m_functions.TryGetValue(item, out m_impl))
      {
        // Function exists and is registered (e.g. pi, exp, etc.)
        return;
      }
 
      // Function not found, will try to parse this as a number.
      s_strtodFunction.Item = item;
      m_impl = s_strtodFunction;
    }
 
    public static void addFunction(string name, ParserFunction function)
    {
      m_functions[name] = function;
    }
 
    public double getValue(string data, ref int from)
    {
      return m_impl.evaluate(data, ref from);
    }
 
    protected virtual double evaluate(string data, ref int from)
    {
      // The real implementation will be in the derived classes.
      return 0;
    }
 
    private ParserFunction m_impl;
    private static Dictionary<string, ParserFunction> m_functions = new Dictionary<string, ParserFunction>();
 
    private static StrtodFunction s_strtodFunction = new StrtodFunction();
    private static IdentityFunction s_idFunction = new IdentityFunction();
  }
 
  class StrtodFunction : ParserFunction
  {
    protected override double evaluate(string data, ref int from)
    {
      double num;
      if (!Double.TryParse(Item, out num)) {
        throw new ArgumentException("Could not parse token [" + Item + "]");
      }
      return num;
    }
    public string Item { private get; set; }
  }
 
  class IdentityFunction : ParserFunction
  {
    protected override double evaluate(string data, ref int from)
    {
      return Parser.loadAndCalculate(data, ref from, Parser.END_ARG);
    }
  }
 
  class PiFunction : ParserFunction
  {
    protected override double evaluate(string data, ref int from)
    {
      return 3.141592653589793;
    }
  }
  class ExpFunction : ParserFunction
  {
    protected override double evaluate(string data, ref int from)
    {
      double arg = Parser.loadAndCalculate(data, ref from, Parser.END_ARG);
      return Math.Exp(arg);
    }
  }
  class PowFunction : ParserFunction
  {
    protected override double evaluate(string data, ref int from)
    {
      double arg1 = Parser.loadAndCalculate(data, ref from, ',');
      double arg2 = Parser.loadAndCalculate(data, ref from, Parser.END_ARG);
 
      return Math.Pow(arg1, arg2);
    }
  }
  class SinFunction : ParserFunction
  {
    protected override double evaluate(string data, ref int from)
    {
      double arg = Parser.loadAndCalculate(data, ref from, Parser.END_ARG);
      return Math.Sin(arg);
    }
  }
  class SqrtFunction : ParserFunction
  {
    protected override double evaluate(string data, ref int from)
    {
      double arg = Parser.loadAndCalculate(data, ref from, Parser.END_ARG);
      return Math.Sqrt(arg);
    }
  }
  class AbsFunction : ParserFunction
  {
    protected override double evaluate(string data, ref int from)
    {
      double arg = Parser.loadAndCalculate(data, ref from, Parser.END_ARG);
      return Math.Abs(arg);
    }
  }
но проблема вот в чем
как я поняла это описывается отдельный класс
но как его переделать на язык си шарп и как связать эти два кусочка не понимаю
может кто то подскажет ??
0
cpp_developer
Эксперт
20123 / 5690 / 1417
Регистрация: 09.04.2010
Сообщений: 22,546
Блог
28.04.2017, 21:51
Ответы с готовыми решениями:

Ввод массивов через множество textBox, подсчёт суммы, и вывод через listBox. Ошибка при вводе через textBox
Создал я кучу текст боксов, там происходит ввод каждого элемента массива. И вывод через листбокс По идее должен...

Ввод функции в textbox и ее вычисление
У меня задача в том, чтобы написать программу, которая выполняла бы метод дихотомии. Алгоритм простой. Но у меня возникла сложность в том,...

Как в VBA в поле Textbox сделать запрет на ввод более одного слова (или запрет на ввод пробелов)?
Добрый день. Нужно, чтобы в поле TextBox можно было ввести не более одного слова (в противном случае выводится сообщение). Приведенный ниже...

1
Эксперт .NET
6691 / 4102 / 1607
Регистрация: 09.05.2015
Сообщений: 9,575
28.04.2017, 23:05
Цитата Сообщение от DariaGris Посмотреть сообщение
но как его переделать на язык си шарп
Он и так на C#.
Цитата Сообщение от DariaGris Посмотреть сообщение
как связать эти два кусочка не понимаю
Не пробовали посмотреть там где взяли этот класс? Там же были примеры использования...

Добавлено через 1 минуту
https://msdn.microsoft.com/ru-... 73716.aspx
http://download.microsoft.com/... t.1015.zip

Добавлено через 2 минуты
C#
1
double result = Parser.Process(textBox1.Text);
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
raxper
Эксперт
30234 / 6612 / 1498
Регистрация: 28.12.2010
Сообщений: 21,154
Блог
28.04.2017, 23:05
Помогаю со студенческими работами здесь

Ввод в TextBox
Как разрешить ввод только латинских букв и цифр в TextBox? Предложили такую идею: Private Sub TextBox1_KeyPress(ByVal KeyAscii As...

Ввод матрицы в textbox
Ребят, такая проблема не могу ввести матрицу в текстбокс. Размерность ввожу с помощью текстбоксов, всё ок. Вот что у меня получилось: ...

Ввод числа pi в textbox
вычисляю интеграл от синуса. Подскажите как можно ввести число pi с клавиатуры? или только возможен ввод 3,14?

Ввод переменной из TextBox
В итоге в лейбл добавляется 10 нулей вместо нужных значений при любых числах в текст боксах, не могу понять что не так private...

Контролируемый ввод в TextBox
Всем привет ,есть интерессный вопрос как сделать так чтобы в TextBox можно было ввести определённые слова т.е например Английский...


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

Или воспользуйтесь поиском по форуму:
2
Ответ Создать тему
Новые блоги и статьи
Установка Qt Creator для C и C++: ставим среду, CMake и MinGW без фреймворка Qt
8Observer8 05.04.2026
Среду разработки Qt Creator можно установить без фреймворка Qt. Есть отдельный репозиторий для этой среды: https:/ / github. com/ qt-creator/ qt-creator, где можно скачать установщик, на вкладке Releases:. . .
AkelPad-скрипты, структуры, и немного лирики..
testuser2 05.04.2026
Такая программа, как AkelPad существует уже давно, и также давно существуют скрипты под нее. Тем не менее, прога живет, периодически что-то не спеша дополняется, улучшается. Что меня в первую очередь. . .
Отображение реквизитов в документе по условию и контроль их заполнения
Maks 04.04.2026
Алгоритм из решения ниже реализован на примере нетипового документа "ПланированиеСпецтехники", разработанного в конфигурации КА2. Данный документ берёт данные из другого нетипового документа. . .
Фото всей Земли с борта корабля Orion миссии Artemis II
kumehtar 04.04.2026
Это первое подобное фото сделанное человеком за 50 лет. Снимок называют новым вариантом легендарной фотографии «The Blue Marble» 1972 года, сделанной с борта корабля «Аполлон-17». Новое фото. . .
Вывод диалогового окна перед закрытием, если документ не проведён
Maks 04.04.2026
Алгоритм из решения ниже реализован на примере нетипового документа "СписаниеМатериалов", разработанного в конфигурации КА2. Задача: реализовать программный контроль на предмет проведения документа. . .
Программный контроль заполнения реквизитов табличной части документа
Maks 02.04.2026
Алгоритм из решения ниже реализован на примере нетипового документа "СписаниеМатериалов", разработанного в конфигурации КА2. Задача: 1. Реализовать контроль заполнения реквизита. . .
wmic не является внутренней или внешней командой
Maks 02.04.2026
Решение: DISM / Online / Add-Capability / CapabilityName:WMIC~~~~ Отсюда: https:/ / winitpro. ru/ index. php/ 2025/ 02/ 14/ komanda-wmic-ne-naydena/
Программная установка даты и запрет ее изменения
Maks 02.04.2026
Алгоритм из решения ниже реализован на примере нетипового документа "СписаниеМатериалов", разработанного в конфигурации КА2. Задача: при создании документов установить период списания автоматически. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru