[英]Creating a simple equation calculator with C#
So this is a bit of homework I have. 因此,这是我的一些作业。 I have to create a calculator application that asks for user input then calculates it.
我必须创建一个计算器应用程序,要求用户输入然后进行计算。 The input must be in an equation format.
输入必须为公式格式。 For example: " x = 3 + 8 ", " x = 6 - 3 " or x = " 6 - 3 * 9 ".
例如:“ x = 3 + 8”,“ x = 6-3”或x =“ 6-3 * 9”。 My approach to this problem is to first break down the string user input and store it into an array of char:
我对这个问题的处理方法是首先分解字符串用户输入,并将其存储到char数组中:
private char[] userInput;
string input = Console.ReadLine();
input = input.Replace(" " ,"");
userInput = input.ToCharArray();
At this point, userInput will contain all char from input. 此时,userInput将包含来自输入的所有字符。 Next, I look for the variable of equation by looping through the array, this should give me the first alphabet character it found:
接下来,我通过遍历数组来查找方程变量,这应该给我找到的第一个字母字符:
char var = 'x';
for (int i = 0; i < userInput.Length; i++)
{
char c = userInput[i];
if (Char.IsLetter(c)){
var = c;
break;
}
}
Next, I will break the equation up with variable one side and all of the number and operator in the other side, separated by '=', then add all number and operator to a new char array: 接下来,我将用变量一侧分解等式,而将另一边的所有数字和运算符分开,用“ =”分隔,然后将所有数字和运算符添加到新的char数组中:
//get '=' position
int equalPos = 0;
for (int i = 0; i < userInput.Length; i++)
{
char c = userInput[i];
if (Char.IsSymbol(c))
{
if (c.Equals('='))
{
equalPos = i;
break;
}
}
}
//add equation to new array
rightSide = new char[userInput.Length-equalPos];
int a = 0;
for (int i = equalPos + 1; i < userInput.Length; i++)
{
char c = userInput[i];
rightSide[a] = c;
a++;
}
At this point, the rightSide array will contain all of the number and operator as character. 此时,rightSide数组将包含所有数字和运算符作为字符。 I can calculate this part by using
System.Data.DataTable().Compute()
. 我可以使用
System.Data.DataTable().Compute()
来计算这部分。 However, if I am not allowed to use any library, how could I implement this? 但是,如果不允许我使用任何库,该如何实现呢? The equation should only contain 1 variable(always appear on the left side of the equation), four basic operators (+-/*) and no parenthesis.
该方程式应仅包含1个变量(始终出现在方程式的左侧),四个基本运算符(+-/ *)且不带括号。
If you first split the string by the =
operator you will get the right and left hand side. 如果首先用
=
运算符分割字符串,则将获得右侧和左侧。 So on the right hand side of the equation, if the equation is 'x = 6 * 2 + 1', we have '6 * 2 + 1', so we can compute that and follow standard BIDMAS rules using a loop and switch: 因此,在等式的右侧,如果等式为'x = 6 * 2 + 1',则为'6 * 2 + 1',因此我们可以计算该值,并使用循环和开关遵循标准BIDMAS规则:
i have removed all error checking, this solution is for when a user inputs a perfect equation in the form 'x = {equation}' or '{equation} = x' 我已删除所有错误检查,此解决方案适用于用户以'x = {equation}'或'{equation} = x'形式输入完美方程式的情况
Also to note, a string
is a char[]
还要注意,
string
是char[]
//get user input
Console.Write("Enter equation:");
string input = Console.ReadLine();
string[] splitInput = input.Split('=');
int index = char.IsLetter(splitInput[0].Replace(" ", "")[0]) ? 1 : 0;
string sideWithEquation = splitInput[index];
//Compute right hand side
string[] equation = sideWithEquation.Split(' ');
Using BIDMAS, and ignoring brackets and indices, we compute divison and multiplication first. 使用BIDMAS,并忽略方括号和索引,我们首先计算除法和乘法。
//compute for * and /
for (int i = 1; i < equation.Length - 1; i++)
{
string item = equation[i];
int num = 0;
switch (item)
{
case "*":
num = Convert.ToInt32(equation[i - 1]) * Convert.ToInt32(equation[i + 1]);
break;
case "/":
num = Convert.ToInt32(equation[i - 1]) / Convert.ToInt32(equation[i + 1]);
break;
}
if (num > 0)
{
equation[i - 1] = "";
equation[i] = "";
equation[i + 1] = num.ToString();
}
}
And then we comoute for addition and subtraction 然后我们加减法
//Now compute for + and -
equation = string.Join(" ", equation).Split(' ');
for (int i = 1; i < equation.Length - 1; i++)
{
string item = equation[i];
int num = 0;
switch (item)
{
case "+":
num = Convert.ToInt32(equation[i - 1]) + Convert.ToInt32(equation[i + 1]);
break;
case "-":
num = Convert.ToInt32(equation[i - 1]) - Convert.ToInt32(equation[i + 1]);
break;
}
if (num > 0)
{
equation[i - 1] = "";
equation[i] = "";
equation[i + 1] = num.ToString();
}
}
and then to display the value of x to the user again 然后再次向用户显示x的值
string total = string.Join("", equation);
//display what x is
Console.WriteLine($"x = {int.Parse(total)}" );
Your answer can be divided into two parts First How to convert char array to a string type Second How to convert a string to a executable code block For the first part use this method: 您的答案可以分为两部分: 第一如何将char数组转换为字符串类型第二如何将字符串转换为可执行代码块对于第一部分,请使用以下方法:
char[] chars;
string s = new string(chars);
For the Second part IT IS TOO DIFFiCULT to find a way without any pre-written code to do so then you must use Microsoft.CSharp.CSharpCodeProvider to compile code on-the-fly. 对于第二部分, 它太难找到一种没有任何预编写代码的方法,那么您必须使用Microsoft.CSharp.CSharpCodeProvider即时编译代码。 In particular, search for CompileAssemblyFromFile .
特别是,搜索CompileAssemblyFromFile 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.