Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

solving a math expression

Tags:

c#

math

I want to evaluate a math expression which the user enters in a textbox. I have done this so far

string equation, finalString;
equation = textBox1.Text;
StringBuilder stringEvaluate = new StringBuilder(equation);
stringEvaluate.Replace("sin", "math.sin");
stringEvaluate.Replace("cos", "math.cos");
stringEvaluate.Replace("tan", "math.tan");
stringEvaluate.Replace("log", "math.log10");
stringEvaluate.Replace("e^", "math.exp");
finalString = stringEvaluate.ToString();
StringBuilder replaceI = new StringBuilder(finalString);
replaceI.Replace("x", "i");

double a;
for (int i = 0; i<5 ; i++)
 {
  a = double.Parse(finalStringI);
  if(a<0)
    break;
 }

when I run this program it gives an error "Input string was not in a correct format." and highlights a=double.Parse(finalStringI);

I used a pre defined expression a=i*math.log10(i)-1.2 and it works, but when I enter the same thing in the textbox it doesn't. I did some search and it came up with something to do with compiling the code at runtime.

any ideas how to do this? i'm an absolute beginner. thanks :)

like image 745
St.SJ Avatar asked Mar 20 '26 07:03

St.SJ


1 Answers

The issue is within your stringEvaluate StringBuilder. When you're replacing "sin" with "math.sin", the content within stringEvaluate is still a string. You've got the right idea, but the error you're getting is because of that fact.

Math.sin is a method inside the Math class, thus it cannot be operated on as you are in your a = double.Parse(finalStringI); call.

It would be a pretty big undertaking to accomplish your goal, but I would go about it this way:

  1. Create a class (perhaps call it Expression).
  2. Members of the Expression class could include Lists of operators and operands, and perhaps a double called solution.
  3. Pass this class the string at instantiation, and tear it apart using the StringBuilder class. For example, if you encounter a "sin", add Math.sin to the operator collection (of which I'd use type object).
  4. Each operator and operand within said string should be placed within the two collections.
  5. Create a method that evaluates the elements within the operator and operand collection accordingly. This could get sticky for complex calculations with more than 2 operators, as you would have to implement a PEMDAS-esque algorithm to re-order the collections to obey the order of operations (and thus achieve correct solutions).

Hope this helps :)

like image 118
Fishz Avatar answered Mar 22 '26 20:03

Fishz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!