0

OK so I'm fairly new to c# in the big scheme of things. I have encountered one of the first things I'm not 100% sure on how to overcome. At the moment I have a program that asks the user to input a number. This is fine if the user inputs something that can be classified as a double. However, I am unsure how to work around fractions and equations, ie; (5*3)+12 with my code looking like...

Console.Write("Enter an equation: ");
double ans = Convert.ToDouble(Console.Readline());
Console.WriteLine("The answer is " + ans)

This doesn't compute with int or double, also I'm aware that the answer to the example given is a integer, however I want it to be classified as a Double so I can get an exact answer when the equation isn't as clean. How would I get around doing this?

TOASTED PIE
  • 37
  • 1
  • 8
  • 1
    At your level of understanding you are probably better to just find a library that can figure out maths equations. there is no build in support for parsing equations like this, or you will have to build it your self. – TheGeneral Sep 04 '18 at 08:22
  • 1
    This is no easy task in c#. It isn't a language that will help you in any way to parse and process the input string. Quite different from various script laguages. - The only simple solution is to make SQL do some (limited) work for you. [See here](https://stackoverflow.com/questions/5838918/evaluate-string-with-math-operators) - A proper c# parser is possible and there are many around but you'll have a hard time to grasp how they work. For a very limited expression set you can do it yourself, but onnce you allow parenthesis things get harder.. – TaW Sep 04 '18 at 08:23
  • 1
    _" there is no build in support for parsing equations like this"_ That's not entirely true. I think there are dupe questions and I saw solutions using [DataTable](https://stackoverflow.com/a/18796518/982149) to have equations computed. – Fildor Sep 04 '18 at 08:23
  • 1
    First thing it came to my mind is Reverse Polish Notation. 12 years ago I implemented it in a webforms, got no code to make a working answer tho. – Cleptus Sep 04 '18 at 08:26
  • 1
    Hehe, RPL also need a user to input it ;-) – TaW Sep 04 '18 at 08:27
  • 1
    Another possible duplicate: https://stackoverflow.com/q/355062/982149 – Fildor Sep 04 '18 at 08:27

0 Answers0