0

Simple string calculator

Hi For my school assignment I have to make a simple calculator that reads a string. The string can have up to 3 operators (^,*,/,-,+) and up to 4 numbers. I have written the code that that checks if the input can be calculated and I have also coded that the string gets broken down into two arrays. One holds operators and the other holds numbers. I am having problem with an algorithm that calculates. I don't know how to prioritise the math solving part of it: ^ --> * --> / > + --> - Here is my code in SoloLearn: https://code.sololearn.com/cdeM01v9kqXh/#cs Here is the part of the code that needs to be worked on: /* Solving this problem: 5 + 2 / 3 ^ 4 Arrays contain: numbers = 5, 2, 3, 4 operators = +, /, ^ */ static double Calculate(double[] numbers, char[] operators) { double result = 0; //here comes the code to solve the math problem above return result; } Although it would be awesome I'm not asking you to write the code for me. I just need guidance on how to solve this problem. Thank you very much for your help! :D

24th Jan 2020, 12:12 AM
Martin Ferenec
Martin Ferenec - avatar
1 Réponse
+ 5
Pseudo code for you: 1. based on your array method: 1.1 loop over operators array. 1.2 if operator is ^, 1.3 record its index, remove ^ from operator array 1.4 in the number array, take the two adjacent number out, insert the calculation result into number array. 1.5 now the arrays are shorten. 1.6 loop over operator array 1.7 check if there is * or / (note that * is not > /, they have same precedence). 1.8 do similar thing to 1.3 and 1.4 1.9 do similar thing to 1.6 to 1.8 for + or -
24th Jan 2020, 1:34 AM
Gordon
Gordon - avatar