Click here to Skip to main content
15,890,336 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi, I'm using c# and I want to convert the user input string into a Mathematical equation. So, when the user input a math equation I want to store it as
a code(or in a text file so the user can use the equation later on to
evaluate values).

Ex) Enter your equation:
user: y=3x+2
Enter a value: 1
y at x=1 is 5

I want a way to use user's equation to evaluate it at certain values, such as x=1,2,3
If you don't know the answer please direct me into the right path,

I appreciate your time

What I have tried:

static void Main(string[] args)
        {
            string function = "";
            double value = 0;

            Console.WriteLine("Enter your function: ");
            function = Console.ReadLine();
            Console.WriteLine("Enter your value: ");
            value = Convert.ToDouble(Console.ReadLine());

        }
Posted
Updated 29-Apr-19 22:14pm

Unlike Javascript, C# can't do this.

Programmatically Invoke the C# Compiler – Doug Holland – An Architects Perspective[^]

Running arbitrary code is a lot of work. You're better off parsing the text as it's entered and writing code to do the calculation. Creating a calculator UI is the easiest way to do this
 
Share this answer
 
In addition to solution #1 by Christian Graus, i'd suggest to take a look at these articles:
A Calculation Engine for .NET[^]
Parsing Mathematical Expressions in VB.NET: Mission Possible[^]
Math Parser .NET C#[^]
C# - A Split-and-Merge Expression Parser in C#[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900